O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required