2012-06-08 75 views
1
class Curious 
    def calculation 
    def calculation 
     @retrieved_value 
    end 
    @retrieved_value = #some kind of intensive process 
    end 
end 

這樣做,外部方法將在第一次運行,內部方法將提供值的後續時間。在一個非嵌套方法中做這件事的優點或缺點是什麼@retrieved_value ||= #some kind of intensive processRuby範圍化的方法值技術

+0

「嵌套方法」可能是一個壞名詞,因爲該方法在「封閉」方法的範圍之外是可用的。 –

回答

2

您正在爲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 
1

國際海事組織幾乎沒有優勢,缺點是乍一看有點不透明。

根據密集過程的性質,可能會有一些範圍優勢。