Alias in Ruby

Tram Ho

Have you used alias in ruby ​​yet? , so let’s find out today

1.Alias ​​in Ruby

In this article, I will show you the following:

  • The alias keyword
  • The alias_method keyword
  • aliases and scopes
  • aliases behind the scene

2.The alias keyword

Ruby provides us with alias keywork to deal with methods and attributes

Here we have defined the Book#book_name method and defined a bookname alias for this method. So now we have bookname is alias of book_name method and name is alias of bookname Therefore, when we call name or bookname will return the same result.

3.The alias_method method

Like alias keywork we also define the Book#book_name method and define the bookname and name as alias of mehtod. We easily see that alias_method takes String and Symbol as parameters, this helps Ruby identify alias or alias_mehtod

4.Alias ​​and scopes

In fact, Module#alias_method has a different way of working from alias keywork in a scope called scope. Consider the following example:

Here we can see that when calling the alisa_method method in the Device#alias_description method identifies the alias defined on the describe method on the Microwave#description method and not on Device#description .

Now let’s see what happens with alias keyword:

We can see when calling alias in Device#alias_description method, the alias describe the Device#description , not the Microwave#description

5.Aliases behind the scene

Let’s go back to the Book class example to find out what happens alias is defined.

Behind the scene username alias is considered a method. In ruby, the method primer will be inserted into a table to keep track of all the methods in your program. This table is called method_entry table.

So the book_name method is a new entry inserted into the method_entry table. Will include the following:

  • Identify the method `book_name ‘
  • The content of the Book#book_name method
  • Book class

That is how alias keyword and alias_method can determine the existing alias method. Now we look at the new entry alias bookname includes:

  • bookname the bookname method
  • The content of the Book#book_name method
  • Class Book

That’s how alias keyword and alias_method method determine aliases for an existing method. Note that the entry contains more information than I have described to keep it simple. We focus on the alias keyword.

Draft link:

Share the news now

Source : Viblo