我有一个属性列表。每个属性都将被设置为一个空数组,我想将元素推送到每个数组。
我想出了如何使用instance_variable_set
创建动态数组,但我无法将元素推送到它。
这就是我的所作所为:
attributes = ["eye","hair_color","hair_size","hair_type"]
i = 0
attributes.each do |a|
# Dynamic arrays are created, like: @eye = []
instance_variable_set("@#{a}", [])
# My attempt to push element
"@#{a}".push(i)
i += 1
end
如何将元素推送到那些动态数组?
答案 0 :(得分:2)
instance_variable_get("@#{a}").push(i)
将有效
答案 1 :(得分:1)
Petr Balaban说得对。我想我也会注意到你可以each_with_index
而不是手动设置和递增i
:
attributes = ["eye","hair_color","hair_size","hair_type"]
attributes.each_with_index do |a,i|
# Dynamic arrays are created, like: @eye = []
instance_variable_set("@#{a}", [])
# As Petr noted...
instance_variable_get("@#{a}").push(i)
end
答案 2 :(得分:1)
另一种方法是:
attributes = %w|eye hair_color hair_size hair_type|
attributes.each_with_index do |a, idx|
self.class.send :attr_accessor, a.to_sym
public_send "#{a}=", idx
(public_send a) << idx
end
现在您可以通过getter访问这些变量:
hair_size
#⇒ 2