From: "Brian Schröder" Date: 2005-08-13T00:22:33+09:00 Subject: Re: eval, attr_* like methods On 12/08/05, Patrick Gundlach wrote: > Dear all, > > I'd like to create methods similar to the attr_* way. I'd like to > write > > class Foo > lookup_meth :bar, :baz > > def some_other_methods > .... > end > > end > > The lookup_meth should define for class Foo methods such as > > def bar > # tricky lookup stuff > return value > end > def bar=(obj) > @bar=obj > end > > > How would I write such lookup_meth? I've been playing a bit with eval, > but I didn't get it quite right. > > Patrick > > class Object def self.lookup_meth(*args) args.each do | name | eval %( def #{name} @#{name} ||= '24' end def #{name}=(arg) @#{name} = arg end ) end end end class Test lookup_meth :test1, :test2 def testme p self.test1 self.test1 = 42 p self.test1 end end Test.new.testme => "24" 42 Hope that helps, Brian -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/