动态设置Ruby对象的属性

时间:2011-10-21 12:41:03

标签: ruby dynamic

如何在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

3 个答案:

答案 0 :(得分:74)

使用send

def set_property(obj, prop_name, prop_value)
    obj.send("#{prop_name}=",prop_value)
end

答案 1 :(得分:3)

如果情况允许使用实例方法,则以下内容不会过于冒犯:

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')

答案 2 :(得分:1)

这个答案(https://stackoverflow.com/a/7466385/6094965)对我有用:

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

attribute必须是String。因此,如果您通过Symbol s(像我这样)的数组进行迭代,则可以使用to_s

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