Search code examples
arraysrubyenumerator

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?


Solution

  • 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]