0.2 Implicit and Explicit Blocks

Converting implicit blocks to explicit

Sometimes, the performance benefits of implicit block invocation are outweighed by the need to have the block accessible as a concrete object.

Ruby makes it very easy to convert blocks from implicit to explicit and back again, but requires special syntax for this.

Let's start with converting implicit to explicit.

Example Code:

Output Window

Now, the other way - explicit to implicit.

Example Code:

Output Window

So from these two examples, we derive a simple set of syntactic rules to convert blocks from one form to the other:

  1. The block should be the last parameter passed to a method.
  2. Placing an ampersand (&) before the name of the last variable triggers the conversion.

Let's do an exercise where you get to try this yourself.

We have a method called filter that accepts an explicitly passed block. We look to the block to tell us whether a value from the array should be accepted or rejected.

The Array#select method does exactly this but requires an implicit block. Try converting the explicit block into an implicit block and passing it on to Array#select.

Hint

Convert the explicit block to implicit by using & when passing it on to Array#select.

Output Window

Ok, let’s make this more complicated by changing our filter method itself to a block, and make the incoming block that does the filtration an implicitly passed one. Here, you’ll need to convert the block passed to Filter from implicit to explicit, then back again.

Sounds complicated? Yes, the conversion of blocks from implicit to explicit and back again can be confusing. It's simpler to focus on making the tests pass and let the learning be a part of that process.

Hint

You'll need to do &block twice.

Output Window

Congratulations, guest!


% of the book completed

or

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