Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A few examples of Ruby's procs, blocks and lambdas (irc question)
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