Ruby blocks vs lambdas

It is possible to define and use first-class functions in Ruby. They are defined using a familiar lambda notation (see below). You can pass as many functions as you want to a function. Note that to call the function, you use call method, just like for a block. Syntactically, however, blocks are different from lambdas and allow you to write more natural code where blocks are used as a "loop" body. You cannot do it with a lambda.

Lambda can be used to pass the "combine" function to a traverse-like general function in NestedArray. Then the "traverse" function can be used to generate all of the methods you are trying to define. If you are using this approach, don't forget about the "seed" parameter to "traverse".


#################### Optional material ##################################
###### may be used to write a traverse-like function in #################
###### Nested Array to write all other methods as calls to traverse #####
 
# creating a function that you can pass to another function
add_two = lambda {|x| x + 2}
p add_two.call(5)

repeat = lambda {|y, z| y.call(y.call(z))}

# functions can now be passed around 
# cannot do it with blocks :-(
def call_two_functions(f1, f2) 
 return f2.call(f1, 5)
end

p call_two_functions(add_two, repeat)

CSci 4651 course.