I'm looking for a elegant way to assign the value stored inside an Hash into a pre-existed object. Just to be clear, if I have an object, say obj with two attributes, say name and age, I want to assign this values coming from an hash without do something like:
obj.name = hash[:name]
obj.age = hash[:age]
Thanks for your attention. Simone
Best bet is probably to simply define a method like update_attributes
which takes a hash and does it inside an instance method of the class.
Expanding on what others have written and what you seem to need I think your best bet would be:
hash.keys.each do |key|
m = "#{key}="
obj.send( m, hash[key] ) if obj.respond_to?( m )
end
This will account for:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With