Forum: Ruby dynamically calling methods that require a block

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A70410682bd132d5edf76b42189ebb45?d=identicon&s=25 Barun Singh (barunio)
on 2009-04-29 02:31
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..
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2009-04-29 03:08
(Received via mailing list)
Barun Singh wrote:
>
> 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
A70410682bd132d5edf76b42189ebb45?d=identicon&s=25 Barun Singh (barunio)
on 2009-04-29 03:14
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!


Joel VanderWerf wrote:
> Barun Singh wrote:
>>
>> 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
This topic is locked and can not be replied to.