Created
December 9, 2014 16:53
-
-
Save mehdi-farsi/a78ab065a673558b43cb to your computer and use it in GitHub Desktop.
Difference between Proc and Lambda
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
# Procs and Lambdas. They are both a Proc object. | |
# | |
# The main differences: | |
# | |
# 1- Lamdbas are strict about argument number instead of Procs. | |
# 2- Lambda :return returns out the scope. Proc :return returns out of the calling scope. | |
# Lamdbas are strict about argument number instead of Procs. | |
l = lambda { |word| puts word } | |
l.call('Mehdi') # output: Mehdi | |
l.call('Mehdi', 'Farsi') # ArgumentError: wrong number of arguments (2 for 1) | |
p = Proc.new { |word| puts word } | |
p.call('Mehdi', 'Farsi') # output: Mehdi | |
# Lambda :return exits out the scope. | |
# Proc :return exits out of the calling scope. | |
def lambda_return_test | |
puts "Before lambda call." | |
lambda {return}.call | |
puts "After lambda call." | |
end | |
def proc_return_test | |
puts "Before proc call." | |
Proc.new {return}.call | |
puts "After proc call." | |
end | |
lambda_return_test # output: Before lambda call. After lambda call. | |
proc_return_test # output: Before proc call. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment