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.
Now, the other way - explicit to implicit.
So from these two examples, we derive a simple set of syntactic rules to convert blocks from one form to the other:
- The block should be the last parameter passed to a method.
- 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
.
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.