From: Robert Klemme Date: 2005-09-20T01:06:37+09:00 Subject: Re: help with tricky proc/binding issue Pit Capitain wrote: > Ara.T.Howard schrieb: >> >> i'm trying to be able to define a proc that can be called in the >> context of self, eg: >> >> block = lambda{ p 42 } >> an_obj.instance_eval &block >> >> but which can also be called with arguments, for example (imaginary >> ruby): >> >> b = lambda{|x| p [x, y]} >> >> class C >> def y; 42; end >> end >> >> c = C::new >> x = 42 >> >> c.arg_instance_eval(x, &b) #=> [42, 42] >> >> any ideas? > > Tom (aka Trans) recently mentioned that he changed procs into methods > in order to get what you want. Here's a quick hack, not efficient and > not thread-safe, but maybe a start: > > class Object > def arg_instance_eval( *args, &block ) > c = class << self; self; end > c.send( :define_method, :arg_instance_eval_method, &block ) > arg_instance_eval_method( *args ) > ensure > c.send( :remove_method, :arg_instance_eval_method ) > end > end Hacky but nice! For thread safety how about: class Object def arg_instance_eval( *args, &block ) c = class << self; self; end meth = "__m_#{Thread.current.object_id}_#{rand 666}" c.send( :define_method, meth, &block ) send( meth, *args ) ensure c.send( :remove_method, meth ) end end Kind regards robert