7.2 Blocks in Ruby

Lambdas vs. Blocks

A lambda is a piece of code that you can store in a variable, and is an object. The simplest explanation for a block is that it is a piece of code that can't be stored in a variable and isn't an object. It is, as a consequence, significantly faster than a lambda, but not as versatile and also one of the rare instances where Ruby's "everything is an object" rule is broken.

As with most things in programming, there is more to this story, but blocks are an advanced topic so lets keep things simple for now. If you're interested in studying blocks in more detail, take a look at our chapter on blocks in our book "Ruby Primer: Ascent" which addresses intermediate and advanced topics.

Let's look at an example of a block that does the same thing as the lambda you wrote in the previous exercise.

Example Code:

Output Window

Let's list the ways in which this example is different from the last exercise that we did when learning about lambdas.

  • There's no lambda.
  • There's something new called yield.
  • There's a method that has the body of a lambda immediately after the parameter list, which is a little weird.

Skipping the details

It turns out that one of the most common uses for a lambda involves passing exactly one block to a method which in turn uses it to get some work done. You'll see this all over the place in Ruby - Array iteration is an excellent example.

Ruby optimizes for this use case by offering the yield keyword that can call a single lambda that has been implicitly passed to a method without using the parameter list.

If you'll review the example in the previous section, you'll notice the same pattern - one method, one block passed to it outside of the parameter list, and with the block called using yield.

Now for some practice. Using what you've learned from earlier examples and exercises, make the tests pass.

Output Window

Congratulations, guest!


% of the book completed

or

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