Alias Keyword in Ruby

Tram Ho

You can give an alternative name to a Ruby method in two ways:

  • alias (keyword)
  • alias_method

But why are there two ways to achieve a common goal? Let’s explore their differences to understand better!

The alias Keyword

First we have the alias , which is a Ruby keyword (like if , def , class , etc.) It looks like this:

Now calling print_something would be like calling puts

Alias has some interesting features as follows:

  • It has a special syntax
  • It can be used anywhere
  • It is possible to alias global variables (But don’t do that)

Valid syntax:

Note that there is no comma between arguments like in a regular method.

If you want to dynamic method names, you can do it like this …

The other looks bad, so you need to use alias_method to do this.

The alias_method Method

Next we have alias_method .

You cannot use this method in an instance method . It can only be definded within a class or module

Here is the description from the documentation:

alias_method: “Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden. ”

For example:

It will set alias for the puts method to print_something in the Foo class

You can also use strings as arguments instead of symbols

For example:

alias vs alias_method

So when does the difference happen?

  1. When you want to create an alias with dynamically name (eg “abc # {rand}”)
  2. When you define alias inside a method

We saw how to use alias to create dynamic method name above, alias_method provides a more flexible syntax.

For example:

However, as mentioned above, alias_method cannot be used inside a method, you will get the following error:

undefined method ‘alias_method’ for # (NoMethodError)

Here is a solution:

However, using alias is much more concise

So the biggest difference between them is:

  • A method defined by the alias will belong to the class in which the alias is used
  • A method defined by alias_method will belong to self , or the current class at the time the code is run

So what does this mean?

If you use alias in superclass then when you call alias in subclass you will call method in parent class

For example:

Aliasing Makes a Copy Of The Method

As described by alias_method & alias , Ruby creates a copy of the method, not just a copy of the method name.

For example:

Now that we’ve set alias x to bacon , let’s see what happens if we override bacon :

bacon returns a new value and x does not.

References

https://www.rubyguides.com/2018/11/ruby-alias-keyword/

Share the news now

Source : Viblo