gpt4 book ai didi

ruby - 我应该使用 alias 还是 alias_method?

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:15 26 4
gpt4 key购买 nike

我找到了一篇关于 aliasalias_method 的博文。如该博客文章中给出的示例所示,我只是想将一个方法作为同一个类中另一个方法的别名。我应该使用哪个?我总是看到使用 alias,但有人告诉我 alias_method 更好。

别名的使用

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

Blog post link here

最佳答案

alias_method 可以根据需要重新定义。 (它在 Module 类中定义。)

alias 的行为会根据其作用域而变化,并且有时无法预测。

结论:使用 alias_method - 它为您提供了更多的灵 active 。

用法:

def foo
"foo"
end

alias_method :baz, :foo

关于ruby - 我应该使用 alias 还是 alias_method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com