Created
September 12, 2013 16:47
-
-
Save peterjwest/6540612 to your computer and use it in GitHub Desktop.
Understanding blocks in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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