Lambdas are essentially annonymous Ruby functions that take in blocks. Among other things, they let you define and execute blocks of code.

Making a Lambda #

There’s two basic syntaxes for making a lambda, the standard and shorthand. Both are ultimately the same.

lambda = lambda {}  # Standard
lambda = -> {} # Shorthand

You can also include arguments for the lambda. If you don’t use it with the right number of arguments, it throws an error.

lambda = -> x, y {
doubled_x = x * 2
doubled_x + y

As with most Ruby code, if there’s multiple lines, the last line is implicitly returned.

lambda = -> x, y {  doubled_x = x * 2  doubled_x + y}

If you use a lambda, know you have to use .call on it.

# With above example, 4)
# 8

Lambdas Vs Procs #

Lambdas are technically different versions of Proc objects, so remember these subtle differences.

Declaration #

Simply replace lambda or -> with and adjust the curly brackets a little around any arguments.

lambda_1 = -> { 2 + 2 }
lambda_2 = -> x, y { x + y }

proc_1 = { x + y }
proc_2 = { |x, y| x + y }

Arguments #

Lambdas throw errors if you don’t include the exact number of arguments. Procfiles skip over them and, if possible, complete and run the block anyway.

Explicit Returns #

Using an explicit return for a Proc pulls you entirely out of a method it may be being used in. Lambdas keep going.

def call_proc
puts "Before proc"
my_proc = { return 2 }
puts "After proc"

p call_proc
# Prints "Before proc" but not "After proc"