DEV Community

Vishal
Vishal

Posted on

Aliases in Ruby

Aliasing in Ruby provides a method to give an alternative name to a method.

There are two ways to achieve it:

  • alias

  • alias_method

alias

alias is a Ruby keyword

Simple way to use it is to provide an alias to an existing method:

This is useful for simple use cases where supposedly you aren’t happy with a long method name that you have to reuse in your code. By providing an alias to a short name, you can make your code more readable and save the burden of using the longer name.

alias_method

alias_method provides a more dynamic approach to programming for Classes and Modules. For example, if there exists a Cat class with a speak method. You will need to use the speak method in your code but you aren’t happy with the implementation of the method.

In the above code we re-implement the speak method, and the alias_method will create a copy of the original speak method to cat_speak. Then you can redefine the speak method with your own implementation and use it in your code.

Cat.new.speak will now use your implementation. This is useful for overriding existing instance methods and is useful in cases where you will need to add more functionality while preserving the existing the namespaces.

Top comments (0)