Iterating over an array
Let’s define a simple Array and call
each on it:
We get an instance of
Enumerator class. We can use the
next method on it and if we use it more than 3 times we get a
So what we can do to create a cyclic enumerator to repeat our collection?
We can cover our
next method using some metaprogramming magic, like this:
and the response is as expected:
This is a dirty trick, because
next is a special keyword in Ruby and covering it with our own method is not a good idea.
Unfortunately, I couldn’t find a way to use all of the
Enumerable API magic with this approach. I have to dig deeper into this. :)