Implementing Lax

Now that you understand how generators work, let’s turn our attention back to the Enumerator::Lax implementation. You wouldn’t have to use Enumerator::Generator directly, since that is taken care for us by the yielder object.

Let’s think about how the client would use your code. In fact, we will try to mimic the real implementation as far as possible. Therefore, here’s an example:

 1.upto(Float::INFINITY)
  .lax
  .map { |x| x*x }
  .map { |x| x+1 }
  .take(5)
  .to_a

This should return [2, 5, 10, 17, 26].

Here’s where the sleight of hand comes in. When the lax method is invoked, an instance of the Lax enumerator is returned. When map is called, this method is called on a Lax instance, not the map defined on the enumerable. ...

Get Mastering Ruby Closures now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.