Lambdas
The following is a collection of some aspects of lambdas.
Lambdas without arguments
l = lambda { puts "Hello I'm a lambda." }
or
l = lambda do
puts "Hello I'm a lambda."
end
Lambdas with arguments
l = lambda { |x| puts "Hello I'm a lambda and I was called with the parameter #{x}" }
or
l = lambda do |x|
puts "Hello I'm a lambda and I was called with the parameter #{x}"
end
two parameters
l = lambda do |x,y|
puts "Hello I'm a lambda and I was called with the parameter #{x} and #{y}"
end
Alternatives for calling/invoking a lambda
l.call( "param" ) # with parameter
l.call # no parameter
or
l.yield( "param" ) # with parameter
l.yield # no parameter
or
l.( "param" ) # with parameter
l.() # no parameter
or
l[ "param" ] # with parameter
l[] # no parameter
Lambdas support default arguments
l = lambda { |x='hello world'| puts x }
Block-local variables
Block-local variables are defined after a semicolon in the block’s parameter list.
l = lambda { |x;locvar| puts x }
square = "this is a square"
sum = 0
[1,2,3,4].each do |val|
square = val * val
sum += square
end
# square => 30
# sum => 30
square = "this is a square"
sum = 0
[1,2,3,4].each do |val;square|
square = val * val
sum += square
end
# square => "this is a square"
# sum => 30
Stabby lambda
An alternative, more compact form of defining a lambda.
l1 = -> a, b { a+b }
l2 = ->( a, b ) { a+b }
Lambdas have built-in currying
add = lambda { |a,b| a+b }
add.call( 10, 20 ) # => 30
increment = add.curry.call( 1 )
increment.call( 4 ) # => 5
add5 = add.curry.( 5 )
add5.( 40 ) # => 45