alias versus alias_method

Posted by patjoyce
Jan 22, 2008

Last week Ian and I were running into a problem with alias_method. It turned out that we were passing the method name to alias method as you would to alias, instead of passing a string or a symbol of the method name. Here is the correct usage of alias and alias method

  
  alias new_method_name old_method_name
  alias_method :new_method_name, :old_method_name
  alias_method 'new_method_name', 'old_method_name'
  

Here is the blog post that pointed out our error. It is in Spanish, so for the first time ever all that time I spent learning Spanish helped me as a programmer ;).

For the benefit of English speakers I decided to translate the blog post. Here is the translated text:

alias and alias_method do the same thing: copy a method and assign it a different name.

  
  class Test
    def test
      puts "hello" 
    end
    alias test_copy test
    alias_method :test_copy2, :test
  end

  Test.new.test        # > "hello" 
  Test.new.test_copy   # > "hello" 
  Test.new.test_copy2  # > "hello" 
  

That piqued my curiosity to know the difference between alias and alias_method. It turns out that they are the same, except that:

  1. alias is a reserved keyword in Ruby
  2. alias takes the method identifiers as parameters, without the need to use symbols or strings (for example in “def method_name”, method_name is an identifier and not a string or a symbol) This behavior can be pretty confusing when you’re starting out.
  3. alias_method is a method of the class Module
  4. alias_method takes its parameters separated by comma, just like any other method.

The consequences are simple:

  • alias_method can be redefined, and alias can’t.
  • alias can be used incorrectly (outside the context of method definitions)

By being a method of Module, alias_method makes it easier to use it correctly: in the context of method definition of a class or module.

Conclusion: In the majority of cases, alias_method is what you need.

Comments

Leave a response

  1. EmmanuelOga January 22, 2008 @ 03:57 PM

    I’m happy my post was helpful, and also that you could read it even when it is written in spanish :)

    Greets!

Comment