views:

268

answers:

2

I came across the following while reading about how easy it is to redefine methods in Ruby:

class Array
  alias :old_length :length
  def length
    old_length / 2
  end
end
puts [1, 2, 3].length

Sure, it's a bad idea, but it makes the point. But it bothered me that we switch between :length and length and :old_length and old_length so easily. So I tried it this way:

class Array
  alias old_length length
  def length
    old_length / 2
  end
end
puts [1, 2, 3].length

It works just fine - apparently just like the first version. I feel like there's something obvious that I'm missing, but I'm not sure what it is.

So, in a nuthsell, why are :name and name interchangeable in these cases?

+3  A: 

alias is a primitive that gets special handling, and apparently can take both symbols and bare names. The related alias_method is just an ordinary method, and has to use ordinary syntax.

alias_method :old_length, :length
Justin Love
+5  A: 

A method isn't a symbol, but its name is. Just writing length calls the method length. To specify the name of the method rather than perform the method, you use a symbol.

class Array
  def show_the_difference
    puts length
    puts :length
  end
end

['three', 'items', 'here'].show_the_difference
# prints "3" for the first puts and then "length" for the second

The case you found with alias is an exception, just because alias works differently from everything else in the language.

Chuck
Perfect: that helps a lot, and it's not _so_ obvious that I feel bad for not knowing it already.
Telemachus