문제

Suppose I have an array

array = [1,2,3]

I need to create such a enumerator that will return values in cyclic manner:

array.next #=> 1
array.next #=> 2
array.next #=> 3
array.next #=> 1
array.next #=> 2
...

I believe there's a neat solution for that

도움이 되었습니까?

해결책

Array#cycle / Enumerable#cycle does what you are looking for:

e = [1,2,3].cycle  #=> #<Enumerator: [1, 2, 3]:cycle>

e.next             #=> 1
e.next             #=> 2
e.next             #=> 3
e.next             #=> 1
e.next             #=> 2

(1..3).cycle returns equivalent values.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top