Loop through array elements

I would like to cycle @aon 0to 2: 0, 1, 2, 0, 1, 2.

def set_a
  if @a == 2 
    @a = 0
  else
    @a = @a + 1
  end
end

Maybe there is a better way?

+5
source share
1 answer
(0..2).cycle(3) { |x| puts x } #=> 0,1,2,0,1,2,0,1,2

item = [0, 1, 2].cycle.each

item.next #=> 0
item.next #=> 1
item.next #=> 2
item.next #=> 0
...
+18
source

All Articles