Andrey Khataev
Andrey Khataev

Reputation: 1343

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?

Upvotes: 0

Views: 255

Answers (1)

moveson
moveson

Reputation: 5213

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]

Upvotes: 1

Related Questions