Created
February 26, 2014 05:27
-
-
Save ogryzek/9224008 to your computer and use it in GitHub Desktop.
Ruby Procs and 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
# What's the difference between procs and lambdas? | |
# | |
# To really understand the difference, put it to use. | |
# irb is great for this. | |
# In irb, instantiate a Lambda and a Proc | |
l = lambda {|x, y| x.times {puts y}} | |
p = Proc.new {|x, y| x.times {puts y}} | |
# See that they are both of the same class | |
l.class | |
p.class | |
# Call each of them using correct and incorrect parameters | |
# to see which one gives and error, and which passes silently | |
l.call 1, 2 | |
l.call 1, 2, 3, 4 | |
p.call 1, 2 | |
p.call 1, 2, 3, 4 | |
# Define a method that takes a parameter and runs some code without | |
# passing params to the proc | |
def proc_tester_without_params(some_proc) | |
a = 3 | |
b = 2 | |
puts a + b | |
some_proc.call | |
c = a * b | |
puts c | |
end | |
# Define a method that takes a parameter and runs some code that | |
# passes too many params to the proc | |
def proc_tester_with_many_params(some_proc) | |
a = 3 | |
b = 2 | |
puts a + b | |
some_proc.call(1,2,3,4) | |
c = a * b | |
puts c | |
end | |
# Pass the proc and the lambda into the methods and observe the outcome. | |
# Note that there is no significance of the variables a, b, c. They are | |
# Just to give some output, to see what happens when we call our proc and | |
# our lambda in a block without giving valid params | |
proc_tester_without_params l | |
proc_tester_without_params p | |
proc_tester_with_many_params l | |
proc_tester_with_many_params p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment