« Back to Index

Ruby: pass a block to a function that has zero arity (i.e. don’t define &block inside of our initialize method). The point of this demonstration is that you are able to pass a block through to another method whilst not initially defining an argument for the block to be passed by. This way we gain better performance (calling a proc is very slow compared to yielding), and regardless we’re not able to pass a yield through to another method.

View original Gist on GitHub

Pass block with zero arity.md

I saw this in some code written by BBC principle developer @kenoir and later located the following useful post: http://mudge.name/2011/01/26/passing-blocks-in-ruby-without-block.html

class Foo
  def initialize
    bar &Proc.new # voodoo
  end
  def bar(&block)
    block.call
  end
end

Foo.new { puts "hai" }

In short, the reason it works is this:

If Proc.new is called from inside a method without any arguments of its own, it will return a new Proc containing the block given to its surrounding method.

Very nice!