From: "David A. Black" Date: 2008-08-27T00:18:50+09:00 Subject: Re: Passing a block with define_method Hi -- On Wed, 27 Aug 2008, David A. Black wrote: > Hi -- > > On Wed, 27 Aug 2008, James Coglan wrote: > >>> module_eval a string. >> >> >> >> I'm actually wrapping existing methods so I need to use define_method to >> retain access to the old method. Here's my (broken) code so far: >> >> module Continuations >> def accepts_continuation(*args) >> args.each do |method_name| >> func = instance_method(method_name) >> define_method(method_name) do |*params, &block| >> value = func.bind(self).call(*params) >> end >> end >> end >> end > > In Ruby 1.9 you can do this: > >>> func = ->(*a,&block) { block.call if block; puts a } > => # >>> C = Class.new { define_method(:hi, &func) } > => C >>> C.new.hi(10) { puts "In block" } > In block > 10 > > The ->(){} thing lets you create a lambda with method-argument > semantics. Actually the fix is in: you can now (and I think permanently) do this in 1.9 without the ->(){}. >> class C; define_method(:hi) {|*a,&block| block.call if block; puts >> a }; end => # >> C.new.hi(10) { puts "In block" } In block 10 I'd lost track of where this stood -- I'm very glad to see that it's there in the block syntax (thanks to Eric Mahurin's patch, if I'm not mistaken). David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL See http://www.rubypal.com for details and updates!