define_method to define a method to pass a block to another method

J

John J. Franey

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
 
P

Paul Novak

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

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.
 
J

John J. Franey

Paul said:
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 :) . 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
 
G

George

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top