From: matt@... (matt neuburg) Date: 2006-10-17T13:45:05+09:00 Subject: Re: dynamically assigning instance variables (redux) 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 Wow, that was way cool. I think we can make it shorter (esp since he only wants attr_readers) and faster (no point generating the singleton class every time thru the loop): class Foo def initialize( hash={} ) singleton_class = class << self; self; end hash.each do |key,value| instance_variable_set( "@" + key, value ) singleton_class.class_eval { attr_reader key } end end end f = Foo.new "name"=>'whee', "age"=>12 p f.age, f.name # => works f.name = "no, it's a reader" # => error, as desired But pls note that I'm just imitating; the self-returning singleton class was totally beyond me! m. -- matt neuburg, phd = matt@tidbits.com, http://www.tidbits.com/matt/ Tiger - http://www.takecontrolbooks.com/tiger-customizing.html AppleScript - http://www.amazon.com/gp/product/0596102119 Read TidBITS! It's free and smart. http://www.tidbits.com