如何在 ruby 的循环中动态访问模型属性?

How to access Model attributes dynamically in a loop in ruby?

我的模型class:

class item
  attr_accessor :item_name
  attr_accessor :item_url
  attr_accessor :item_label
  .
  . 
end

当我想给这个attributes.Insted赋值的时候一个一个赋值即item.item_name="abc".

我想用硬编码名称将所有属性放入循环中,并从其他来源分配。

['item_url','item_url','item_label'].each do |attr|
   item.attr=values from some other source #error on this line
   #or
   item."#{attr}"=values from some other source #error on this line
end

它们都不起作用。欢迎任何建议

您可以使用 send:

item.send("#{attr}=", value)

http://ruby-doc.org/core-2.2.3/Object.html#method-i-send

你可以这样做:

 item.send((attr + "="), values from some other source)

或:

hash = {}
['item_url','item_url','item_label'].each do |attr|
  hash[attr] = value
end
item.attributes = hash

attr_accessor 为作为 setter 方法给出的每个属性定义 #attr=。因此,例如,您可以使用 #item_name= 为 item_name 赋值。要在给定方法名称的字符串或符号的实例上调用方法,请在实例上调用 __send__

['item_url','item_url','item_label'].each do |attr|
  item.__send__("#{attr}=", value)
end

send 也可以,但我更喜欢 __send__,因为 send 更有可能被意外覆盖。