Skip to content

Instantly share code, notes, and snippets.

@deepak
Created October 11, 2010 11:02
Show Gist options
  • Save deepak/620356 to your computer and use it in GitHub Desktop.
Save deepak/620356 to your computer and use it in GitHub Desktop.
block_calling_syntax.rb
# -*- coding: utf-8 -*-
# http://yehudakatz.com/2010/02/25/rubys-implementation-does-not-define-its-semantics/
# Nathan de Vries, Posted February 25, 2010, 2:27 am
# From PickAxe:
# “If the last argument to a method is preceded by an ampersand, Ruby assumes that it is a Proc object. It removes it from
# the parameter list, converts the Proc object into a block, and associates it with the method.”
# Hence being referred by some as the “blockinator”. i.e. take the argument prefixed by “&” and convert it to a block so that
# the receiver can invoke it via “yield”. This idea of conversion to a block is what steered people towards overriding
# to_proc (for better or worse).
def foo(&block)
yield 10
end
foo {|x| puts "x: #{x}" }
p = Proc.new {|x| puts "x: #{x}" }
foo(&p)
foo(&p) {|x| puts "x: #{x}" } # error - test_proc.rb:21: both block arg and actual block given
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment