Andrey Khataev Andrey Khataev - 15 days ago 6
Ruby Question

How to cycle array enumeration in Ruby

I want to implement such enumerator that rewinds from last back to first element and continues looping, such an infinite loop. How could it be done?

Answer

There's a method that does exactly that:

Enumerable#cycle

>> a = [1, 2, 3]
>> a.cycle.first(7)
=> [1, 2, 3, 1, 2, 3, 1]
Comments