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?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
aliasis a keyword and it is lexically scoped. It means it treatsselfas the value ofselfat the time the source code was read. In contrastalias_methodtreatsselfas the value determined at the run time.Overall my recommendation would be to use
alias_method. Sincealias_methodis a method defined in classModuleit can be overridden later and it offers more flexibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With