From: Sean O'Halpin Date: 2008-05-10T10:04:28+09:00 Subject: Re: Method lookup from a Lambda On Fri, May 9, 2008 at 11:01 PM, John Conti wrote: >> >> "Let's " + instance_eval(&grunt) + " it" > > Is there a way to pass arguments to &grunt during the invocation? The > call method allows arguments to be passed to the lambda's that expect > them. While my example does not show such a lambda, this is a feature I > currently require. If grunt did require arguments, how could I pass > them? Hi, You need instance_exec, which is native in 1.9 but has to be implemented in Ruby in 1.8. The version below is the best one I have to hand. (There may be a better one on Mauricio's blog but eigenclass.org is coming up with a hiki error at the moment so I can't check). Regards, Sean # # instance_exec for ruby 1.8 by Mauricio Fernandez # http://eigenclass.org/hiki.rb?bounded+space+instance_exec # thread-safe and handles frozen objects in bounded space # class Object module InstanceExecHelper; end include InstanceExecHelper def instance_exec(*args, &block) begin old_critical, Thread.critical = Thread.critical, true n = 0 methods = InstanceExecHelper.instance_methods # this in order to make the lookup O(1), and name generation O(n) on the # number of nested/concurrent instance_exec calls instead of O(n**2) table = Hash[*methods.zip(methods).flatten] n += 1 while table.has_key?(mname="__instance_exec#{n}") ensure Thread.critical = old_critical end InstanceExecHelper.module_eval{ define_method(mname, &block) } begin ret = send(mname, *args) ensure InstanceExecHelper.module_eval{ remove_method(mname) } rescue nil end ret end end