gpt4 book ai didi

ruby - 在 Ruby 中跨类的多个实例内存数据的好方法是什么?

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

考虑:生成数据的对象的许多实例。每次运行只生成一次该数据会很棒。

class HighOfNPeriods < Indicator
def generate_data
@indicator_data = DataStream.new
(0..@source_data.data.count - 1).each do |i|
if i < @params[:n_days]
...
@indicator_data.add one_data
end
end

有不同的 HighOfNPeriods 实例,它们具有不同的 params 和不同的 @source_data

指标的使用方法如下:

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 存储数据,但这并不是我现在真正想要的方式,因为:

  1. 并不是所有生成的数据都可以提前生成,因为有 参数的排列太多。看看它是否有更有意义 之前已生成,然后根据需要生成(并保存)。
  2. 生成数据不需要很长时间。它可以生成一次并使用 每次运行数百次。
  3. 从对象内部访问数据比从数据库中提取数据更快。

ruby 1.9.3

最佳答案

如果您无法在实例级别记​​忆它,请向上一级并使用类实例。

class Foo
# I used *args here for simplicity of the example code.
def generate_data *args
if res = self.class.cache[args]
puts "Data in cache for #{args.inspect} is #{res}"
return res
end

puts "calculating..."
p1, p2 = args
res = p1 * 10 + p2
self.class.cache[args] = res
res
end

def self.cache
@cache ||= {}
@cache
end
end


puts Foo.new.generate_data 1, 2
puts Foo.new.generate_data 3, 4
puts Foo.new.generate_data 1, 2
# >> calculating...
# >> 12
# >> calculating...
# >> 34
# >> Data in cache for [1, 2] is 12
# >> 12

关于ruby - 在 Ruby 中跨类的多个实例内存数据的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13552585/

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