Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY way to assign hash values to an object

Tags:

ruby

hash

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

like image 273
Simone Di Cola Avatar asked Sep 08 '10 16:09

Simone Di Cola


1 Answers

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:

  • not having all the attributes of the class in the hash at all times, and
  • any number of keys in the hash (not just :name, etc)
like image 139
rfunduk Avatar answered Oct 07 '22 01:10

rfunduk