-
-
Save kvirani/5119310 to your computer and use it in GitHub Desktop.
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
# Lambdas, Proc.new, and Blocks - Bitmaker breakout session | |
# Friday March 8, 2013 | |
## LAMBDAS | |
# Basic Usage: | |
# Think of lambdas as methods that have no name and instead they can be assigned to a variable and thus be passed around. | |
l = lambda {"do or do not"} | |
puts l.call # returns => do or do not | |
### DO-MATH EXAMPLE (WITH A LAMBDA) ### | |
# Below is a generic math function which accepts 2 numbers and a math function | |
# This function "calls" the math lambda, passing num1 and num2 as inputs to the lambda. | |
# It does not know or care about what math does, just that it is a lambda that it can "call" | |
def do_math(num1, num2, math) | |
math.call(num1, num2) | |
end | |
# Now let's use the do_math method, passing 2, 3, and an `adder` function | |
adder = lambda {|num1, num2| num1 + num2} # adds two numbers and returns the result | |
result = do_math(2, 3, adder) | |
puts result | |
# We could just pass the lambda right into do_math instead of assigning it to the adder variable first: | |
result = do_math(2, 3, lambda {|num1, num2| num1 + num2}) | |
puts result | |
## Consider lambdas and Proc.new the SAME (for the time being). So this will give us the same behavior and result: | |
result = do_math(2, 3, Proc.new {|num1, num2| num1 + num2}) | |
puts result | |
## BLOCKS | |
# Think of blocks as in-line, single-use versions of lambdas | |
### DO-MATH EXAMPLE (WITH A BLOCK) ### | |
# Note how the method do_math2 below does NOT mention that it accepts or expects a block. | |
# Any method can be passed a block (of code); whereas lambdas need to be passed in as normal arguments like num1 and num2 | |
def do_math2(num1, num2) | |
yield(num1, num2) ### yield is similar to .call except used to call the block. | |
end | |
result = do_math2(2,3) { |num1, num2| num1 + num2 } | |
puts result | |
## This can also be re-written as: | |
result = do_math2(2,3) do |num1, num2| | |
num1 + num2 | |
end | |
puts result | |
## This is called Functional programming, where CODE is also passed around instead of just DATA. | |
## If this is still unclear, that's okay. It is one of the more complicated parts of Ruby and usually takes time to sink in. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment