dynamic-动态设置Ruby Obj的属性

如何在Ruby中动态设置对象属性,例如

def set_property(obj, prop_name, prop_value)
    #need to do something like > obj.prop_name = prop_value 

    #we can use eval but I'll prefer a faster/cleaner alternative:
    eval "obj.#{prop_name} = #{prop_value}"
end
neebz asked 2020-08-10T16:00:30Z
4个解决方案
77 votes

使用发送:

def set_property(obj, prop_name, prop_value)
    obj.send("#{prop_name}=",prop_value)
end
lucapette answered 2020-08-10T16:00:35Z
12 votes

Object#instance_variable_set是您要寻找的产品,并且是您想要的更清洁的版本。

例:

your_object = Object.new
your_object.instance_variable_set(:@attribute, 'value')
your_object
# => <Object:0x007fabda110408 @attribute="value">

Ruby documentation about Object#instance_variable_set

Jochem Schulenklopper answered 2020-08-10T16:02:00Z
4 votes

这个答案([https://stackoverflow.com/a/7466385/6094965)]为我工作:

Object.send(attribute + '=', value)

attribute必须是String。因此,如果要遍历30030030811106739202s阵列(如我),则可以使用to_s

Object.send(attribute.to_s + '=', value) 
Tincho Rockss answered 2020-08-10T16:02:25Z
3 votes

如果情况允许使用实例方法,则以下内容并不令人反感:

class P00t
  attr_reader :w00t

  def set_property(name, value)
    prop_name = "@#{name}".to_sym # you need the property name, prefixed with a '@', as a symbol
    self.instance_variable_set(prop_name, value)
  end
end

用法:

p = P00t.new
p.set_property('w00t', 'jeremy')
Benjineer answered 2020-08-10T16:02:51Z
translate from https://stackoverflow.com:/questions/7849521/set-attribute-dynamically-of-ruby-object