考慮:生成數據的對象的許多實例。每次運行只產生一次這樣的數據是很好的。在Ruby的一個類的許多實例中記憶數據的好方法是什麼?
class HighOfNPeriods < Indicator
def generate_data
@indicator_data = DataStream.new
([email protected]_data.data.count - 1).each do |i|
if i < @params[:n_days]
...
@indicator_data.add one_data
end
end
有不同params
和不同@source_data
的HighOfNPeriods
不同實例。
這裏是指示如何使用:
class Strategy
attr_accessor :indicators
def initialize params
...
end
方法HighOfNPeriods.generate_data
從Strategy
中調用。每個Strategy
都會得到一個新實例HighOfNPeriods
,因此無法將其作爲某種全局值抽出。除此之外,它不應該是全球性的。
unless @indicator_data
不起作用,因爲數據需要在許多HighOfNPeriods
實例中共享。
所以,問題是:
What is a good way to memoize the instance variable `indicator_data`
or the object `HighOfNPeriods` when there are many different instances,
some of which have different data?
一種解決方案是存儲使用ActiveRecord的數據,但是這並不是我真正想在這個時候做的方式,因爲:
- 不所有生成的數據可以預先生成,因爲有太多的params排列。看看它是否已經生成了之前生成的 ,然後根據需要生成(並保存)會更有意義。
- 生成數據並不需要很長時間。它可能會產生一次,每次運行使用 幾百次。
- 從對象中訪問數據比從數據庫中獲取數據要快。
紅寶石1.9.3
請注意,當代碼透明時,實現記憶是非常容易的。我會說你的代碼設計不好,因爲你的'generate_data'方法不接受執行計算所需的參數,並且取決於你的對象的狀態。 – samuil