Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the syntax of Ruby's alias allowed?

Tags:

ruby

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
  1. So why is the alias method get to use a syntax nothing else gets to use?
  2. Is it possible to use this syntax in any other context?
  3. 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.
like image 210
Alex Wayne Avatar asked Nov 22 '12 00:11

Alex Wayne


1 Answers

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 treats self as the value of self at the time the source code was read. In contrast alias_method treats self as the value determined at the run time.

Overall my recommendation would be to use alias_method. Since alias_method is a method defined in class Module it can be overridden later and it offers more flexibility.

like image 60
joelparkerhenderson Avatar answered Nov 14 '22 06:11

joelparkerhenderson