Last active
January 12, 2022 22:06
-
-
Save havenwood/f80308141c8460e3d181 to your computer and use it in GitHub Desktop.
A few examples of Ruby's procs, blocks and lambdas (irc question)
This file contains hidden or 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
def meth &block | |
block | |
end | |
block = meth { 42 } | |
prok = proc { 42 } | |
lamb = lambda { 42 } | |
block.call | |
#=> 42 | |
prok.call | |
#=> 42 | |
lamb.call | |
#=> 42 | |
block.call :extra | |
#=> 42 | |
prok.call :extra | |
#=> 42 | |
lamb.call :extra | |
#>> ArgumentError: wrong number of arguments (1 for 0) | |
block.class | |
#=> Proc | |
prok.class | |
#=> Proc | |
lamb.class | |
#=> Proc | |
block.lambda? | |
#=> false | |
prok.lambda? | |
#=> false | |
lamb.lambda? | |
#=> true | |
def locality_of_return &block | |
block.call | |
:carried_on | |
end | |
locality_of_return { break :ended_early } # block | |
#=> :ended_early | |
locality_of_return &proc { break :ended_early } # proc | |
#*> LocalJumpError: break from proc-closure | |
locality_of_return &lambda { break :ended_early } # lambda | |
#=> :carried_on |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment