Implementing Lazy take

Now that you’ve implemented map, you can have a go at implementing the take method. As its name suggests, Enumerable#take(n) returns the first n elements from the Enumerable. As with the lazy version of map, the lazy version of take also returns a Lax instance, this time wrapping the Enumerable#take method. Here’s how it looks:

 def​ take(n)
  taken = 0
  Lax.new(self) ​do​ |yielder, val|
 if​ taken < n
  yielder << val
  taken += 1
 else
 raise​ StopIteration
 end
 end
 end

The logic for take should be easy enough for you to follow. The interesting thing here is how take signals that the iteration has ended. When taken reaches the limit, a StopIteration exception is raised ...

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.