From: Robert Klemme Date: 2005-10-03T04:41:46+09:00 Subject: Re: Eval and block problems Brian Schr�der wrote: > On 02/10/05, Ryan Leavengood wrote: >> On 10/2/05, Brian Schr�der wrote: >>> Please help me to wrap my mind around this. I want to achieve the >>> following: [code snipped] >>> >>> and have the block from the dynamically created method foo be >>> evaluated in the binding of the instance of A. >>> >>> I'm sure this is possible, but I've never really grocked eval, >>> instance_eval and class_eval. >> >> Good question! Because by researching the answer I learned you can >> just pass a block to define_method: >> >> class A >> def initialize(x) >> @x = x >> end >> >> def self.def_me(cmd, &block) >> define_method(cmd, &block) >> end >> >> def_me("foo") do >> puts "x is #@x" >> end >> end >> >> A.new(1).foo >> A.new(2).foo >> __END__ >> >> But strictly speaking in this case the separate def_me method is >> redundant since you could just call define_method directly. >> >> Ryan >> >> > > Thank you ryan, it is incredible how fast there come really good > answers here. Combining your proposal and davids I have the following. > If I could get rid of the additional method, that would be perfect. Just don't use the block for define_method but invoke it from the closure: class A def self.def_me(cmd,&block) define_method(cmd) do puts "preparation" instance_eval &block end end attr_accessor :name end a=A.new a.name = "Einstein" A.def_me(:foo) do puts @name, self.name end >> a.foo preparation Einstein Einstein => nil Kind regards robert