Skip to content

Instantly share code, notes, and snippets.

@peterjwest
Created September 12, 2013 16:47
Show Gist options
  • Save peterjwest/6540612 to your computer and use it in GitHub Desktop.
Save peterjwest/6540612 to your computer and use it in GitHub Desktop.
Understanding blocks in ruby
# Normally a block is passed after the arguments
[1,2,3].map(){ |i| i.next }
# & passes the argument as a block
[1,2,3].map(&:next)
# & arguments are cast to a Proc
[1,2,3].map(&:next.to_proc)
# Procs are already procs
[1,2,3].map(&Proc.new { |i| i.next })
# But you can cast them too
[1,2,3].map(&Proc.new { |i| i.next }.to_proc)
# Procs can be bound to variables and used elsewhere
x = Proc.new { |i| i.next }
[1,2,3].map(&x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment