From: Holden Glova Date: 2002-06-04T15:54:40+09:00 Subject: Re: dynamic attr_accessor?? On Tue, 04 Jun 2002 02:58, you wrote: > thanks for your tip. > > does one of the two possible solutions have any significant > advantages over the other or is this just a matter of style?? > > is one more like "the ruby way" ?? > > markus > > Yukihiro Matsumoto wrote: > > Hi, > > > > In message "dynamic attr_accessor??" > > > > on 02/06/03, Markus Jais writes: > > |I like to create methods for my class dynamically based on > > |strings I pass to initialize > > > > a) attr_accessor is a method of a class > > b) attr_accessor takes names of accessors > > c) attr_accessor just defines two methods > > > > So the answer should be > > > > easier one: > > > > class Cl > > def initialize(name) > > @name = name > > self.instance_eval " > > def #{name}; @#{name}; end > > def #{name}=(val); @#{name}=val; end > > " > > end > > end > > > > trickier one: > > > > class Cl > > def initialize(name) > > @name = name > > class < > self > > end.module_eval{attr_accessor name} > > end > > end > > > > matz. I personally prefer the non-eval way that Guy Decoux recommend of using type.__send__. Try and not use eval whenever you can IMO - plus I think the clarity is enhanced in many non-eval solutions. irb(main):019:0> class A irb(main):020:1> def initialize(name) irb(main):021:2> @name = name irb(main):022:2> type.__send__(:attr_accessor, "name") irb(main):023:2> end irb(main):024:1> end nil irb(main):025:0> a = A.new('billy') # irb(main):026:0> a.name "billy" irb(main):027:0> a.name = 'Freddy' "Freddy" irb(main):028:0> a.inspect "#" -- Signed, Holden Glova