Is the Ruby length method a symbol? Why: is the length sometimes the same as the length?

I came across the following while reading about how to easily override methods in Ruby:

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

Of course, this is a bad idea, but that makes sense. But it bothered me that we easily switch between :lengthand lengthand :old_lengthand old_length. So I tried it like this:

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

It works great - apparently, as in the first version. I feel that there is something obvious that I am missing, but I'm not sure what it is.

So, in nuthsell, why are :namethey nameinterchangeable in these cases?

+3
source share
2 answers

, . length length. , , .

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

, alias, , , alias , .

+5

alias - , , -, , . alias_method .

alias_method :old_length, :length
+3

Source: https://habr.com/ru/post/1709891/


All Articles