Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Metaprogramming: dynamic instance variable names

Let's say I have the following hash:

{ :foo => 'bar', :baz => 'qux' } 

How could I dynamically set the keys and values to become instance variables in an object...

class Example   def initialize( hash )     ... magic happens here...   end end 

... so that I end up with the following inside the model...

@foo = 'bar' @baz = 'qux' 

?

like image 277
Andrew Avatar asked Jul 19 '11 02:07

Andrew


2 Answers

The method you are looking for is instance_variable_set. So:

hash.each { |name, value| instance_variable_set(name, value) } 

Or, more briefly,

hash.each &method(:instance_variable_set) 

If your instance variable names are missing the "@" (as they are in the OP's example), you'll need to add them, so it would be more like:

hash.each { |name, value| instance_variable_set("@#{name}", value) } 
like image 178
Chuck Avatar answered Oct 19 '22 17:10

Chuck


h = { :foo => 'bar', :baz => 'qux' }  o = Struct.new(*h.keys).new(*h.values)  o.baz  => "qux"  o.foo  => "bar"  
like image 34
DigitalRoss Avatar answered Oct 19 '22 16:10

DigitalRoss