Created
April 19, 2013 15:13
-
-
Save jbinto/5421013 to your computer and use it in GitHub Desktop.
Procs vs Lambdas
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
# 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