Created
March 8, 2013 16:33
Revisions
-
There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,52 @@ l = lambda {"do or do not"} puts l.call #returns => do or do not ########## basic lambda usage l = lambda do |string| if string == "try" return "There's no such thing" else return "Do or do not" end end puts l.call("try") ################ use the lambda function to increment any number passed to it by 1 Increment = lambda {|number| number.next} a = Increment.call(2) puts a ######### demonstrating lambdas def do_math(num1, num2, math) #define a function which accepts three inputs --> num1, num2 and math math.call(num1, num2) #this function "calls" the math function, passing num1 and num2 as inputs end a = do_math(2,3,lambda {|num1, num2| num1 + num2}) ###call the do math function, passing 2, 3, and the lambda function as inputs puts a #### prints the output to the console ######### demonstrating blocks ### think of blocks as in-line, single-use versions of lambdas def do_math2(num1, num2) ##define a function do_math2, which accepts num1, num2 and math yield(num1, num2) ### the yield function returns the outputs of num1 and num2 when passed to a block end b = do_math2(2,3) do |num1, num2| num1 + num2 ### this function takes the outputs from the do_math2 function and then applies them to the following block (looks a lot like a lambda) end ############# demonstrating Proc.new ### essentially replace lambda with Proc.new and it'll work the same way as the previous example. def do_math(num1, num2, math) math.call(num1, num2) end a = do_math(2,3,Proc.new {|n1, n2| n1 + n2}) ### essentially replace Proc.new for lambda puts a #prints the output to the console