From: Phil Tomson Date: 2007-06-26T09:53:11+09:00 Subject: Re: dynamically define attr_accessors on objects? On 6/25/07, Aaron Smith wrote: > How can I dynamically define attr_accessors on an object? > > EX:;: > class Person > attr_accessor :firstname > end > p = Person.new > p.firstname = 'aaron' > p.instance_variable_set(:@lastname, 'smith') > puts p.inspect > puts p.firstname > puts p.lastname > > the last line generates an "undefined method lastname" error.. > > any ideas? > thanks > > -- I suppose you could do something like: class Person def def_accessor name, val=nil self.class.class_eval { attr_accessor name.intern } instance_variable_set ( "@#{name}".intern, val ) end end Then you could do something like: h = { "fooname"=>"Foo", "age"=>28 } h.each {|key,value| p.def_accessor key, value } ...but the other suggestion to use OpenStruct is probably a better idea. Phil