gpt4 book ai didi

Ruby 作用域方法值技术

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:01 24 4
gpt4 key购买 nike

class Curious
def calculation
def calculation
@retrieved_value
end
@retrieved_value = #some kind of intensive process
end
end

执行上述操作时,外部方法将在第一次运行,内部方法将在后续时间提供值。与仅执行 @retrieved_value ||= #some kind of intensive process 的单个非嵌套方法相比,这样做的优点或缺点是什么?

最佳答案

您正在为 Curious 类重新定义 calculation 方法。这将影响其他实例:

a = Curious.new
a.calculation # calls "outer" method, this sets @retrieved_value
a.calculation # calls "inner" method

b = Curious.new
b.calculation # calls "inner" method, @retrieved_value not set

关于Ruby 作用域方法值技术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10950184/

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