Reputation: 187004
This one's been keeping me up at night for a while.
class Foo
def bar
'bar'
end
# What the hell is going on here?!?
alias :baz :bar
end
Foo.new.baz #=> 'bar'
Why does alias
take 2 symbol as arguments, but without a comma separating them? That doesn't seem to be any form of valid syntax in any other context. And in fact, if you do use a comma, it actually throws a syntax error.
alias :bar, :baz
# syntax error, unexpected ','
However, if I try to pass 2 symbol in the same way to my own method, it also explodes:
def somemethod(*args)
:whatever
end
somemethod :a :b
# syntax error, unexpected ':', expecting $end
alias
method get to use a syntax nothing else gets to use?Upvotes: 12
Views: 3211
Reputation: 35443
The reason alias
works is because it's a Ruby keyword, similar to class
, def
, etc. It's not a method.
The alias
keyword doesn't need a comma because the Ruby designers decided it didn't. Keywords are essentially hardcoded in the interpreter.
There is a good reason for alias
when you need to be certain the alias happens at parse time, not runtime.
The alias
keyword may be confusing or surprising. For typical development, I believe it's better to use the Ruby method Module#alias_method
, which does use a comma and works at runtime.
Here's a good blog post about alias
and alias_method
:
This is because
alias
is a keyword and it is lexically scoped. It means it treatsself
as the value ofself
at the time the source code was read. In contrastalias_method
treatsself
as the value determined at the run time.Overall my recommendation would be to use
alias_method
. Sincealias_method
is a method defined in classModule
it can be overridden later and it offers more flexibility.
Upvotes: 18
Reputation: 11904
It's not a method, and those aren't arguments. alias
is one of the few keywords in Ruby (see them all here!). It bothers me as well, so I switched to alias_method
(and there are other arguments for this).
Upvotes: 7