2012-05-29 145 views
5

我想从02循环@a0, 1, 2, 0, 1, 2通过阵列元素循环

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

也许有更好的办法吗?

回答

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 
... 
+1

如果OP不需要使用数组,则也可以是'(0..2).cycle'。另外'cycle'对于循环数量采用可选参数。 –

+0

不错的提示,已更新 – megas

+0

您不需要每个循环都使用.next –