7.1 Lambdas In Ruby

Lambdas

You may have heard of lambdas before. Perhaps you've used them in other languages. Despite the fancy name, a lambda is just a function... peculiarly... without a name. They're anonymous, little functional spies sneaking into the rest of your code. Lambdas in Ruby are also objects, just like everything else! The last expression of a lambda is its return value, just like regular functions. As boring and familiar as that all sounds, it gives us a lot of power.

As objects, lambdas have methods and can be assigned to variables. Let's try it!

Example Code:

Output Window

Cool. Notice that our anticipatorily apologetic string is the return value of the lambda which we see by printing it using puts. Now, while this is a lovely string, perhaps we'd like to return something more interesting. Lambdas take parameters by surrounding them with pipes.

Example Code:

Output Window

Even cooler. Note that we replaced the {} that wrapped the lambda with do..end. Both work equally well, but the convention followed in Ruby is to use {} for single line lambdas and do..end for lambdas that are longer than a single line.

Now go ahead and add a lambda to the following code which increments any number passed to it by 1.

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2024 by Sidu Ponnappa and Jasim A Basheer