From: Paul Brannan Date: 2001-12-08T06:42:57+09:00 Subject: [ruby-talk:27863] Re: Method creation question On Sat, Dec 08, 2001 at 05:40:06AM +0900, Bob Hutchison wrote: > I'd like to write: > > class Foo > myAttr :bar > end > > and have two accessor functions added to class Foo. I know of no way to do it without an eval: class Module def myAttr(symbol) class_eval <<-END def #{symbol} puts "returning #{symbol}" @#{symbol} end def #{symbol}=(value) puts "setting #{symbol}" @#{symbol}=value end END end end class Foo myAttr :foo end f = Foo.new f.foo = 42 #=> setting foo f.foo #=> returning foo The reason you must use an eval is that there currently is no way to get the name of the current function. It should be possible to get this using an extension; I think it's stored in ruby_frame->last_func? Using class_eval, though, is slower to create the methods, but faster to execute them. Paul