From: ara.t.howard@... Date: 2006-10-18T00:04:34+09:00 Subject: Re: dynamically assigning instance variables (redux) On Tue, 17 Oct 2006, Phrogz wrote: > matt neuburg wrote: >> 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 > > /slaps forehead > Of course, very nice :) or, with attributes.rb: harp:~ > cat a.rb require 'rubygems' require 'attributes' class Foo def initialize(h={}) h.each{|k,v| attributes k => v} end end foo = Foo.new 'a' => 4, :k => 2 p foo.a p foo.k harp:~ > ruby a.rb 4 2 ;-) -a -- my religion is very simple. my religion is kindness. -- the dalai lama