gpt4 book ai didi

ruby - self.attribute 与 @attribute 的优势?

转载 作者:数据小太阳 更新时间:2023-10-29 07:02:01 27 4
gpt4 key购买 nike

假设如下:

def create_new_salt
self.salt = self.object_id.to_s + rand.to_s
end

为什么使用“ self ”更好。而不是实例变量“@salt”?

最佳答案

如果已定义,使用 self.salt = 将导致使用 salt= 方法。这对于确保使用 salt= 方法内的任何错误检查/转换很有用。然而,这意味着必须有一个明确的 salt= 方法(例如,可能由 attr_accessor 创建),这不一定是个好主意。

总结:如果你有一个自定义的salt=方法,使用self.salt =;使用 @salt = 如果你确切地知道你想要什么 @salt 是什么,或者如果你没有自定义 salt= 方法。

最后说明:我可能会这样写(在我看来这样更清楚一点)

def create_new_salt
@salt = "#{object_id}#{rand}"
end

编辑:感谢@Chuck 对另一个答案的评论,我修改了它以删除 self.-free 代码 - 这是错误的。

关于ruby - self.attribute 与 @attribute 的优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1877808/

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