# Dynamically calling methods that require a block

**URL:** <https://www.ruby-forum.com/t/dynamically-calling-methods-that-require-a-block/166733>\
**Category:** Ruby\
**Created:** [April 29, 2009, 2:31am UTC](https://www.ruby-forum.com/t/dynamically-calling-methods-that-require-a-block/166733 "2009-04-29T02:31:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![barunio](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/b487fb/32.png) [@barunio](https://www.ruby-forum.com/u/barunio)\
**Post date:** [April 29, 2009, 2:31am UTC](https://www.ruby-forum.com/t/dynamically-calling-methods-that-require-a-block/166733/1 "2009-04-29T02:31:30Z")

</div>

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…

---

<div class="post-metadata">

**Author:** ![barunio](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/b487fb/32.png) [@barunio](https://www.ruby-forum.com/u/barunio)\
**Post date:** [April 29, 2009, 3:08am UTC](https://www.ruby-forum.com/t/dynamically-calling-methods-that-require-a-block/166733/2 "2009-04-29T03:08:05Z")

</div>

Barun S. 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

---

<div class="post-metadata">

**Author:** ![barunio](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/b487fb/32.png) [@barunio](https://www.ruby-forum.com/u/barunio)\
**Post date:** [April 29, 2009, 3:14am UTC](https://www.ruby-forum.com/t/dynamically-calling-methods-that-require-a-block/166733/3 "2009-04-29T03:14:41Z")

</div>

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