Lambdas - Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Lambdas

Lambdas are the more common way of passing blocks around. They are used the same way procs are.

our_lamb = lambda {|x,y| puts x + y}

our_lamb.call(5,7)

12

Let's use a lambda to iterate and change an array of strings to symbols.

ary = ["name", "age", "gender"]

sym = lambda { |x| x.to_sym }

new_ary = ary.collect(&sym)

print new_ary

[:name, :age, :gender]

Procs vs Lambdas

There are two differences you need to know about Procs and Lambdas. Here's an easy way to remember the first one:

Procs are trusting.

Lambdas are trustworthy.

Procs don't care how many arguments you pass to them. They trust you. If you give them too many arguments they will ignore the extra ones. If you don't give them enough arguments, they will give the missing ones the value of nil.

our_proc = Proc.new {|x,y| puts x + y}

our_proc.call(2,4,8)

6

Lambdas on the other hand are suspicious of our shenanigans. They will raise an error if we don't have the correct amount of arguments.

our_lamb = lambda {|x,y| puts x + y}

our_lamb.call(2,4,8)

wrong number of arguments (3 for 2) (ArgumentError)

The other difference is that procs are disobedient. (Not a technical term. Computers only do what you tell them to... For now.) Take a look at the code below.

def trees

leaf = Proc.new {puts "I'm blowing in the wind."}

leaf.call

print "I'm standing still."

end

trees

I'm blowing in the wind.

I'm standing still.

In the method above we've both created a proc and then called the proc. In the proc block we told it to puts a string. It did as we asked and then the method finished by printing the string "I'm standing still.". How is this disobedient? It's not yet. It will be. It will be.