From: Ryan Davis Date: 2006-10-17T14:37:24+09:00 Subject: Re: dynamically assigning instance variables (redux) On Oct 16, 2006, at 8:45 PM, Phrogz wrote: > Bil Kleb wrote: >> Is there a way to dynamically assign instance variables? > [...snip...] >> Actually, I'd like the assignment and make them attr_readers too. > > class Foo > def initialize( hash={} ) > hash.each{ |key,value| > var_name = "@#{key}" > instance_variable_set( var_name, value ) > singleton_class = class << self; self; end > singleton_class.class_eval{ > define_method( key ){ > instance_variable_get( var_name ) > } > define_method( "#{key}=" ){ |new_value| > instance_variable_set( var_name, new_value ) > } > } > } > end > end I find this much too complex with no real need for using singleton_classes (ever, really). Try: class Foo def initialize( hash={} ) hash.each do |ivar, val| self.class.send :attr_accessor, ivar unless respond_to? ivar send "#{ivar}=", val end end end The primary benefit of writing code like this is that you can know what it does in half a glance with no extra thinking. I should also point out that calling a define_method method is about 2x slower than an attr_* method. (not a big deal in this case but take a look at rails' primary_key and think about that impact) > f = Foo.new :name=>'whee', :age=>12 > p f, f.age > #=> # > #=> 12 > f.age=32 > p f > #=> #