Tel*_*hus 3 ruby alias symbols
在阅读有关在Ruby中重新定义方法是多么容易时,我遇到了以下内容:
class Array
alias :old_length :length
def length
old_length / 2
end
end
puts [1, 2, 3].length
Run Code Online (Sandbox Code Playgroud)
当然,这是一个坏主意,但它说得好.但困扰我,我们之间进行切换:length,并length与:old_length和old_length那么容易.所以我这样试了:
class Array
alias old_length length
def length
old_length / 2
end
end
puts [1, 2, 3].length
Run Code Online (Sandbox Code Playgroud)
它工作得很好 - 显然就像第一个版本.我觉得有一些明显的东西让我失踪,但我不确定它是什么.
所以,在nuthsell,为什么:name和name在这些情况下可以互换?
方法不是符号,而是其名称.只需编写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
Run Code Online (Sandbox Code Playgroud)
您找到的案例alias是一个例外,因为alias与该语言中的其他内容的工作方式不同.