Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created May 26, 2014 06:01
Show Gist options
  • Save Integralist/b79b7a7706cc150b457c to your computer and use it in GitHub Desktop.
Save Integralist/b79b7a7706cc150b457c to your computer and use it in GitHub Desktop.
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 c…

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment