在Ruby的工作类的方法,我们必须使用第三方框架,其中有一类的设置是这样的:动态变量访问红宝石
class Foo
attr_accessor :bar
def initialize()
end
end
class Poorly_Designed_Class
attr_accessor :thing1
attr_accessor :thing2
attr_accessor :thing3
attr_accessor :thing4
attr_accessor :thing5
# through :thing_n .. number defined at runtime
def initialize()
@thing1 = Foo.new
@thing2 = Foo.new
@thing3 = Foo.new
@thing4 = Foo.new
@thing5 = Foo.new
end
end
我不知道有多少“东西”直到运行时间。有可能是5或他们可能是50
我想要做的是一样的东西:
pdc = Poorly_Designed_Class.new
for i in 0..numberOfThings do
pdc."thing#{i}".bar = value[i]
end
以上不起作用。
我也尝试通过访问它:
instance_variable_set("pdc.thing#{i}.bar",value)
我了解该类应该使用一个数组或哈希。不幸的是,我无法对班级的设计做任何事情,我们必须使用它。
我试图做甚至可能吗?
首先尝试找出哈希实例变量的名称:'pdc.instance_variables' – nsave