循环遍历数组的元素

时间:2012-05-29 02:43:14

标签: ruby

我想将@a0循环到20, 1, 2, 0, 1, 2

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

也许有更好的方法?

1 个答案:

答案 0 :(得分:18)

(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
...
相关问题