alias versus alias_method
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:
- alias is a reserved keyword in Ruby
- 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.
- alias_method is a method of the class Module
- 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.
More Articles on Software & Product Development
- Agile With a Lowercase “a”
- ”Agile“ is an adjective. It is not a noun. It isn’t something you do, it is something you are.
- How Do You End Up With A Great Product A Year From Now?
- Nail the next two weeks. 26 times in a row.
- Build it Twice
- Resist the urge to abstract until you've learned what is general to a class of problems and what is specific to each problem.