我应该使用 alias 还是 alias_method? [英] Should I use alias or alias_method?
问题描述
我发现了一篇关于 alias
与 alias_method
的博文.如该博客文章中给出的示例所示,我只想将一个方法别名为同一类中的另一个方法.我应该使用哪个?我总是看到使用 alias
,但有人告诉我 alias_method
更好.
I found a blog post on alias
vs. alias_method
. As shown in the example given in that blog post, I simply want to alias a method to another within the same class. Which should I use? I always see alias
used, but someone told me alias_method
is better.
别名的使用
class User
def full_name
puts "Johnnie Walker"
end
alias name full_name
end
User.new.name #=>Johnnie Walker
alias_method 的使用
class User
def full_name
puts "Johnnie Walker"
end
alias_method :name, :full_name
end
User.new.name #=>Johnnie Walker
推荐答案
alias_method
可以根据需要重新定义.(它在 Module
类中定义.)
alias_method
can be redefined if need be. (it's defined in the Module
class.)
alias
的行为会根据其范围而变化,有时可能非常不可预测.
alias
's behavior changes depending on its scope and can be quite unpredictable at times.
结论:使用 alias_method
- 它为您提供了更多的灵活性.
Verdict: Use alias_method
- it gives you a ton more flexibility.
用法:
def foo
"foo"
end
alias_method :baz, :foo
这篇关于我应该使用 alias 还是 alias_method?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!