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
- So why is the
aliasmethod get to use a syntax nothing else gets to use? - Is it possible to use this syntax in any other context?
- What is the benefit of using this odd syntax quirk, when nothing else in the language works this way? I see no discernable benefit to this language inconsistency.
The reason
aliasworks is because it’s a Ruby keyword, similar toclass,def, etc. It’s not a method.The
aliaskeyword 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
aliaswhen you need to be certain the alias happens at parse time, not runtime.The
aliaskeyword may be confusing or surprising. For typical development, I believe it’s better to use the Ruby methodModule#alias_method, which does use a comma and works at runtime.Here’s a good blog post about
aliasandalias_method: