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 Lazy map

Let’s implement method chaining on methods such as map and take. Enumerable::Lax returns a Lax instance, which means we need to define Lax versions of map and take. Each invocation of map and take will in turn return yet another Lax instance. Recall how the original implementation “wraps” each method call with a “lazy layer.” You’ll do exactly the same thing here.

How would the map method in Lax look? Here’s a start:

 def​ map(&block)
 end

You also know that you would need to return a new Lax instance. Also, since map is going to be chained, you should expect that self is going to be another Lax instance:

 def​ map(&block)
» Lax.new(self)
 end

For ...

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