Define_method to define a method to pass a block to another

I would like to define the following method, func, using define_method
instead of def:

def func(i, &block)
wblock(i, &block)
end

def wblock(i, &block)
yield(i)
end

The following didn’t work:

syntax error

define_method(‘func’) do |i,&block|
wblock(i, &block)
end

ruby expects a second parameter, not a block

define_method(‘func’) do |i,block|
wblock(i, &block)
end

Any ideas?

Thanks

On Jun 13, 9:40 am, “John J. Franey” [email protected] wrote:

end

Any ideas?

Thanks

View this message in context:http://www.nabble.com/define_method-to-define-a-method-to-pass-a-bloc
Sent from the ruby-talk mailing list archive at Nabble.com.

Sorry I don’t have time to work out a more complete answer, but check
this out: http://innig.net/software/ruby/closures-in-ruby.rb it is
the best exploration of Ruby closures that I’ve seen.

Regards,

Paul.

Paul N. wrote:

yield(i)
define_method(‘func’) do |i,block|

Sorry I don’t have time to work out a more complete answer, but check
this out: http://innig.net/software/ruby/closures-in-ruby.rb it is
the best exploration of Ruby closures that I’ve seen.

Paul,

Thanks, that’s quite enough :slight_smile: . I read through this and I agree its
quite
an extensive exploration of ‘closure-things’.

I think the answer to my question, then is: define_method cannot define
a
method that accepts a block passed implicitly or using the ‘&’.
define_method can define a method that explicitly accepts a
‘closure-thing’:

define_method(‘func’) do |p1, closure|

closure.call …

end

used this way:

obj.func(1, lambda( {puts “hello”}))

NOT this way:

obj.func(1) {puts “hello”} # the way I wanted

Regards,
John

On 6/15/07, John J. Franey [email protected] wrote:

I think the answer to my question, then is: define_method cannot define a
method that accepts a block passed implicitly or using the ‘&’.

Correct.

In ruby 1.8, blocks can’t accept a block. This feature has been added
in 1.9.

If you need to dynamically define methods which take blocks in 1.8, I
think you’ll need to use #class_eval / #module_eval either with a
block with defs in it (less useful, since locals outside the block
aren’t accesible inside the defs), or with a string argument (with the
usual caveats about evalling strings which might be generated from
user input).

George.