Search code examples
rubyclosuresblock

Can a Ruby method access the implicit block argument?


The implicit block argument passed to a Ruby method can be executed using yield, or its existence can be checked using block_given?. I'm trying to procify this implicit block to pass it to another method.

Is this possible?

(It's access to the implicit block argument I'm asking about. Replacing this with an explicit argument won't cut it.)


Solution

  • You can refer to the block argument via Proc.new. From the docs:

    ::new may be called without a block only within a method with an attached block, in which case that block is converted to the Proc object.

    Example:

    def bar
      yield * 2
    end
    
    def foo
      bar(&Proc.new)
    end
    
    foo(123)
    #=> 456
    

    Note that Proc.new raises an ArgumentError when called without passing a block.