Alex Rivera | Logout

DRY way to assign hash values to an object

Asked 2010-09-08T16:19:53.120
10

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

Edit
Report

2 Answers

13

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)
answered 2010-09-08T16:25:17.243
2

Using instance_variable_set is another option. Here is an example:

class Test; attr_accessor :name, :age; end

hash = {name: 'John', age: 52}

obj = Test.new
hash.each do |k,v|
  obj.instance_variable_set("@#{k}".to_sym, v) # :name is converted to :@name
end

p obj # => #<Test:0x007fd8cbb75b00 @name="John", @age=52> 

The only trick is that instance_variable_set expects a symbol starting with @ so :@name is valid but :name is not.

answered 2012-11-16T18:03:35.463

Your Answer