5
我想从0
到2
循环@a
:0, 1, 2, 0, 1, 2
。通过阵列元素循环
def set_a
if @a == 2
@a = 0
else
@a = @a + 1
end
end
也许有更好的办法吗?
我想从0
到2
循环@a
:0, 1, 2, 0, 1, 2
。通过阵列元素循环
def set_a
if @a == 2
@a = 0
else
@a = @a + 1
end
end
也许有更好的办法吗?
(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
...
如果OP不需要使用数组,则也可以是'(0..2).cycle'。另外'cycle'对于循环数量采用可选参数。 –
不错的提示,已更新 – megas
您不需要每个循环都使用.next –