Forum: Ruby How to get a reference to a block (when no explicit block parameter is used?)

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.
Kenneth McDonald (Guest)
on 2008-11-26 18:29
(Received via mailing list)
In a function, I can find out if a block was given using block_given?,
but there's no way I can find to get hold of that block if it's there--
I can only yield to it, so far as I can tell. I know there has to be a
method somewhere to do this, could some kind soul enlighten me?

Many thanks,
Ken
Jan F. (Guest)
on 2008-11-26 18:36
(Received via mailing list)
Kenneth McDonald <removed_email_address@domain.invalid> wrote:

> In a function, I can find out if a block was given using block_given?,
> but there's no way I can find to get hold of that block if it's there--
> I can only yield to it, so far as I can tell. I know there has to be a
> method somewhere to do this, could some kind soul enlighten me?
>
> Many thanks,
> Ken

def my_meth param, &block
  p block
end

Regards,
Jan F.
Pit C. (Guest)
on 2008-11-26 18:43
(Received via mailing list)
Ken, you can use Proc.new

  http://www.ruby-doc.org/core/classes/Proc.html#M001573

Regards,
Pit
Kenneth McDonald (Guest)
on 2008-11-26 19:00
(Received via mailing list)
Unfortunately, that produces a method that _requires_ a block--I want
one where the block is optional. But thanks for the feedback.

Ken
James C. (Guest)
on 2008-11-26 19:03
(Received via mailing list)
2008/11/26 Jan F. <removed_email_address@domain.invalid>

> def my_meth param, &block
>  p block
> end



The way I understood the question was as follows:

def my_method(arg)
  if block_given?
    yield(arg)
  end
end

How to get a reference to the given block in this situation? This is
especially true if you use define_method, which cannot specify a block
param
(at least not in 1.8). Any suggestions?
Sebastian H. (Guest)
on 2008-11-26 19:05
(Received via mailing list)
Kenneth McDonald wrote:
> Unfortunately, that produces a method that _requires_ a block

No, it does not.

HTH,
Sebastian H.
Yossef M. (Guest)
on 2008-11-26 19:06
(Received via mailing list)
On Nov 26, 10:54 am, Kenneth McDonald
<removed_email_address@domain.invalid> wrote:
> Unfortunately, that produces a method that _requires_ a block--I want
> one where the block is optional. But thanks for the feedback.

Did you try it?

>> my_meth(5) { puts 'hi' }
#<Proc:0x0006ae28@(irb):10>
>> my_meth(5)
nil
Kenneth McDonald (Guest)
on 2008-11-27 05:18
(Received via mailing list)
Whoops, apologies to all. Didn't realize &b arguments were optional.

K
This topic is locked and can not be replied to.