Aliasing methods
In Ruby, you can create an alias for a method using the alias keyword or the alias_method method. This allows you to refer to the same method by different names, which can be useful for readability or to provide backward compatibility when renaming methods.
class MyClass
def hello(name)
"Hello, #{name}!"
end
alias :yo :hello
end
obj = MyClass.new
obj.hello("Alice") # => "Hello, Alice!"
obj.yo("Bob") # => "Hello, Bob!"
class MyClass {
hello(name) {
return `Hello, ${name}!`;
}
}
// JavaScript doesn't have a built-in way to alias methods,
// but we can achieve a similar effect by assigning the method
// to another property on the prototype.
MyClass.prototype.yo = MyClass.prototype.hello;
const obj = new MyClass();
obj.hello("Alice"); // "Hello, Alice!"
obj.yo("Bob"); // "Hello, Bob!"
Another use-case for alias is to preserve the original implementation of a method before overriding it:
class MyClass
def greet(name)
"Hello, #{name}!"
end
alias :original_greet :greet
def greet(name)
"#{original_greet(name)} How are you today?"
end
end
This way, we can still call the original greet method from within the new implementation.
However, after the advent of Module#prepend, the need for method aliasing to preserve original implementations has diminished.
Some examples of methods that are aliased in Ruby's standard library itself include:
- Array#size to Array#length
- Kernel#sprintf to Kernel#format
- Pathname#+ to Pathname#/
- Set#add to Set#<<
History
The alias keyword is one of Ruby's oldest language features and was present in Ruby 1.0 in 1996.