문제

I have an array

arr = [1,2,3,4,5]

and I'm wondering if there is a way to cycle through it so something like:

i = 2
arr[3+n]

would return 1, rather than nil

Is that possible using the index, or even with next?

도움이 되었습니까?

해결책 2

Perform a modulo on the index using the array size:

arr = [1, 2, 3, 4, 5]
arr[5 % arr.size]  #=> 1

다른 팁

It's called cycle:

c = [1,2,3,4,5].cycle
10.times{p c.next}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top