From: "Brian Schröder" Date: 2005-10-03T03:21:26+09:00 Subject: Re: Eval and block problems 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. class A def self.def_me(cmd, &block) define_method("__#{cmd}", &block) private "__#{cmd}" define_method(cmd) do puts "Defined method" send("__#{cmd}") end end def_me("foo") do puts "Here in block" puts "self is #{self}" end end A.new.foo regards, Brian -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/