From: steve Date: 2008-10-30T06:11:31+09:00 Subject: Re: Passing a block with define_method ------=_Part_100715_9810478.1225314736398 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline here's another way to do it: m = instance_method(method_name) define_method "__call__#{method_name}" do |b, *a| begin m.bind(self).call(*a, &b) ensure p :WRAPPED! end end eval <<-EOF def #{method_name} *a, &b __call__#{method_name}(b, *a) end EOF - steve On Tue, Aug 26, 2008 at 10:28 PM, ara.t.howard wrote: > > On Aug 26, 2008, at 8:30 AM, James Coglan wrote: > > Hi list, >> >> I've got a bit of a problem whereby I need to pass a block to a method >> defined using define_method this works: >> >> def some_method(*args, &block) >> # ... >> end >> >> but this does not -- the interpreter complains about unexpected >> ampersands: >> >> define_method(:some_method) do |*args, &block| >> # ... >> end >> >> Is there any way to make this work? I'm doing something a little meta, so >> I >> don't know the name of the method or the number of arguments, so it's all >> got to be dynamic. >> >> >> >> -- >> James Coglan >> > > > a working example: > > cfp:~ > cat a.rb > module Continuations > Funcs = {} > def Continuations.funcs() Funcs end > > def accepts_continuation *argv > argv.flatten.compact.each do |arg| > arg = arg.to_s > klass = Class === self ? self : self.class > Funcs[arg] = klass.send(:instance_method, arg) > klass.module_eval <<-code > def #{ arg }(*a, &b) > Continuations.funcs[#{ arg.inspect }].bind(self).call(*a, &b) > ensure > STDERR.puts 'wrapped!' > end > code > end > end > end > > def foo &b > b.call 'bar' > end > > foo{|bar| puts "foo#{ bar }"} > > include Continuations > accepts_continuation :foo > > foo{|bar| puts "foo#{ bar }"} > > > > cfp:~ > ruby a.rb > foobar > foobar > wrapped! > > > > a @ http://codeforpeople.com/ > -- > we can deny everything, except that we have the possibility of being > better. simply reflect on that. > h.h. the 14th dalai lama > > > > > ------=_Part_100715_9810478.1225314736398--