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:
|||taken = 0|
|||Lax.new(self) do |yielder, val||
|||if taken < n|
|||yielder << val|
|||taken += 1|
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 ...