Functions and Blocks

Lambda in Ruby

A lambda saves a block of code for re-use.

Lambdas are declared and behave similar to blocks and procs.


Syntax
lambdaName = lambda { #block of code }

#convert to block
&lambdaName

#run a lambda
lambdaName.call

Notes

At the return statement, lambdas return control back to the calling method, as opposed to procs, which exit the calling method (applies to call, not to yield).

Lambdas are often used to declare functions on the fly.


Example
def doubleNumber (number)
    calculate = lambda { |x| return x * 2 }
    newNumber = calculate.call(number)

    #this area of code gets reached because it is a lambda
    puts "The original number: #{number}
    return newNumber
end 

See Also
Related

Blocks
Procs

Documentation

Class: Proc - RubyDocs

Add to Slack

< Proc   |   Class Declaration & Structure >

© 2019 SyntaxDB. All Rights Reserved.