Skip to content

Instantly share code, notes, and snippets.

@jbinto
Created April 19, 2013 15:13
Show Gist options
  • Save jbinto/5421013 to your computer and use it in GitHub Desktop.
Save jbinto/5421013 to your computer and use it in GitHub Desktop.
Procs vs Lambdas
# You can return from a lambda, and it will behave as expected.
write_two_words = lambda { |x, y| return "#{x} #{y}" }
puts write_two_words.call("hi", "there") # => hi there
def foo
# If you *explicitly* return from a Proc, you will actually return from the caller.
# Note that if you omit the "return" keyword, it behaves just like a lambda.
write_two_words = Proc.new { |x, y| return "#{x} #{y}" }
puts write_two_words.call("hi", "there")
puts "This never gets written, the Proc made foo return"
end
foo
# A lambda checks the number of arguments
write_two_words = lambda { |x, y| "#{x} #{y}" }
write_two_words.call("hello") # ArgumentError: wrong number of arguments (1 for 2)
# A proc does not check the number of arguments
write_two_words = Proc.new { |x, y| "#{x} #{y}" }
write_two_words.call("hello") # => "hello "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment