From: Robert Klemme Date: 2005-01-13T20:51:17+09:00 Subject: Re: Kernel#eval and class definition "Pit Capitain" schrieb im Newsbeitrag news:41E64CD5.6010703@capitain.de... > Robert Klemme schrieb: > > "Joel VanderWerf" schrieb im Newsbeitrag > > news:41E55294.2040102@path.berkeley.edu... > >>Better, in the sense that it takes a block (see below). But evaling a > >>string to define the body of the class allows you to interpolate. > >> > >>def f(arg) > >> Class.new do > >> define_method :g do arg end > >> end > >>end > >> > >>puts f("hello").new.g # ==> hello > > > > > > You can even use the def syntax: > > > > irb(main):001:0> cl = Class.new do > > irb(main):002:1* def foo() "bar" end > > irb(main):003:1> end > > => # > > irb(main):004:0> cl.new.foo > > => "bar" > > > > That's better because then you can define methods that deal with blocks, > > which you can't with define_method: > > > > irb(main):005:0> cl = Class.new do > > irb(main):006:1* def foo() yield "bar" end > > irb(main):007:1> end > > => # > > irb(main):008:0> cl.new.foo {|x| p x} > > "bar" > > => nil > > The def syntax lets you define methods with blocks, but it doesn't let you use > objects from the defining scope, as Joel has been doing in his example. Note > that he passes an object into the defining method and accesses this very object > from the new class. You can't do that with the def syntax AFAIK. Yeah, true. So then both have their pros and cons. Thanks for the reminder! Kind regards robert