From: "David A. Black" Date: 2005-08-13T02:17:14+09:00 Subject: Re: eval, attr_* like methods --8323328-1026756949-1123867032=:16311 Content-Type: MULTIPART/MIXED; BOUNDARY="8323328-1026756949-1123867032=:16311" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --8323328-1026756949-1123867032=:16311 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Sat, 13 Aug 2005, [ISO-8859-1] Brian Schr=F6der wrote: > 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=3D(obj) >> @bar=3Dobj >> 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} > =09@#{name} ||=3D '24' > end > > def #{name}=3D(arg) > =09@#{name} =3D arg > end > ) > end > end > end > > class Test > lookup_meth :test1, :test2 > > def testme > p self.test1 > self.test1 =3D 42 > p self.test1 > end > end > > Test.new.testme > =3D> > "24" > 42 # However..... p test1 =3D> "24" You've defined them as instance methods of Object, so they appear at the top level. You'd probably want: class Module def lookup_meth(*args) args.each do |arg| define_method(arg) do instance_variable_get("@#{arg}") end define_method("#{arg}=3D") do |v| instance_variable_set("@#{arg}", v) end end end end or similar. David --=20 David A. Black dblack@wobblini.net --8323328-1026756949-1123867032=:16311-- --8323328-1026756949-1123867032=:16311--