Set Attribute Dynamically of Ruby Object
Use send:
def set_property(obj, prop_name, prop_value)
obj.send("#{prop_name}=",prop_value)
end
Object#instance_variable_set()
is what you are looking for, and is the cleaner version of what you wanted.
Example:
your_object = Object.new
your_object.instance_variable_set(:@attribute, 'value')
your_object
# => <Object:0x007fabda110408 @attribute="value">
Ruby documentation about Object#instance_variable_set
If circumstances allow for an instance method, the following is not overly offensive:
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
Usage:
p = P00t.new
p.set_property('w00t', 'jeremy')