dynamically calling methods that require a block

B

Barun Singh

Is it possible to call methods that require block inputs dynamically
without resorting to "eval"? For example, consider:

a = [1,2,3]
a.detect{|x| x > 2}

I want to know if it's possible to do something like the following (this
doesn't work):

a.send:)detect, {|x| x > 2})

I'm using Ruby 1.8.6

Thanks..
 
J

Joel VanderWerf

Barun said:
Is it possible to call methods that require block inputs dynamically
without resorting to "eval"? For example, consider:

a = [1,2,3]
a.detect{|x| x > 2}

I want to know if it's possible to do something like the following (this
doesn't work):

a.send:)detect, {|x| x > 2})

I'm using Ruby 1.8.6

Thanks..

Just pass the block to the send method as you normally would pass a block:

a.send:)detect, &proc {|x| x > 2})
=> 3
a.send:)detect) {|x| x > 2}
=> 3
 
B

Barun Singh

Ah, right I forgot the ampersand. I needed to be able to define the
block separately from the send call, so I tried this:

cond = Proc.new {|x| x > 2}
a.send:)detect, cond)

but I needed that second line to be
a.send:)detect, &cond)

thanks!
 

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

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top