在阅读有关在Ruby中重新定义方法是多么容易时,我遇到了以下内容:
class Array
alias :old_length :length
def length
old_length / 2
end
end
puts [1, 2, 3].length
当然,这是一个坏主意,但它说明了这一点。但令我感到困扰的是,我们很容易在:length
和length
以及:old_length
和old_length
之间切换。所以我这样试了:
class Array
alias old_length length
def length
old_length / 2
end
end
puts [1, 2, 3].length
它工作得很好 - 显然就像第一个版本一样。我觉得有一些明显的东西让我失踪,但我不确定它是什么。
所以,在nuthsell中,为什么:name
和name
在这些情况下可以互换?
答案 0 :(得分:5)
方法不是符号,但其名称是。只需编写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
的工作方式与语言中的其他内容不同。
答案 1 :(得分:3)
alias
是一个得到特殊处理的原语,显然可以同时使用符号和裸名称。相关的alias_method
只是一种普通的方法,必须使用普通的语法。
alias_method :old_length, :length