Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Attribute Dynamically of Ruby Object

Tags:

dynamic

ruby

How can I set an object attribute dynamically in Ruby e.g.

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 
like image 437
neebz Avatar asked Oct 21 '11 12:10

neebz


2 Answers

Use send:

def set_property(obj, prop_name, prop_value)     obj.send("#{prop_name}=",prop_value) end 
like image 167
lucapette Avatar answered Nov 01 '22 01:11

lucapette


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

like image 42
Jochem Schulenklopper Avatar answered Nov 01 '22 01:11

Jochem Schulenklopper