ruby alias and alias_method 1.8.x, 1.9.x, 2.0.x

Moin Moin,

it took me a moment to understand how this is working. Actually there are no good examples for the usage of alias and alias_method in the w3 so I decided to post this here.

The code for the examples can be found here: https://gist.github.com/andywenk/5038259

Here is a basic example for the usage of alias:

The output is:

Example with the usage of alias
I am the total perfect method

The first thing to mention, is that this will not work, when one is writing the alias line before the even_nicer_method. The reason is, that alias is a Ruby keyword and is immediately executed, when the source is parsed. So the method even_nicer_method has to be declared in advance.

Now an example for the usage of alias_method:

The output is:

Example with the usage of alias
AliasMethod::even_nicer_method called

On first sight, it seems to be the same. The big difference is found in scoping. Here is an example using inheritance which is working also in both ways:

The output is for both alias and alias_method:

Example for inheritance
I am the Mother

But when using class methods, things are changing:

In this constructed situation, a class method my_name is defined in MotherScope and is beeing called in ChildScope. So the question is, how self is handled.

The output when using alias in MotherScope.my_name is:

Example for class methods in inheritance (scope!)
I am the Mother

The output when using alias_method in MotherScope.my_name is:

Example for class methods in inheritance (scope!)
I am the Child

Why? Because when using alias, self is the thing when parsing the source code. That means, self “is pointing” to MotherScope. But when using alias_method, the scope is the one found during runtime!

I hope this makes the usage and difference between alias and alias_method clear. While writing this I found these two posts - so yes there are at least some posts ;-):

http://andreacfm.com/2012/11/29/ruby-alias-vs-alias-method/

http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html

Cheers

Published: February 26 2013