From: 7stud -- Date: 2009-09-19T14:58:15+09:00 Subject: Re: Mucking about with dynamically adding methods to objects 7stud -- wrote: > > define_method() to the rescue: > > def talkify(obj, str) > obj_singleton = get_singleton_class(obj) > > obj_singleton.class_eval do > > define_method("talk") do > puts str > end > > end > > Neither of the blocks used with class_eva() or define_method() creates a > new scope, so code inside them can make use of variables defined in the > surrounding scope. > Hmm...I've decided that I find that explanation totally unsatisfying. If define_method() really created a method, then inside the created method str would be undefined. Since str isn't undefined when the talk 'method' is called, define_method() must really create a closure somewhere along the line, i.e. something like a Proc object. Maybe define_method() creates a method that calls a Proc object? For instance, something like this: def talk a_proc.call end where a_proc is created like this: a_proc = Proc.new {puts str} which forms a closure, so all the variables in scope at the time a_proc was created can be referenced inside a_proc. -- Posted via http://www.ruby-forum.com/.