我有一个间隔让我们说(0..3)其中下一个元素是+1,除非是最后一个.然后下一个是0.我通过下面的代码解决了它.只是想知道是否还有其他事情:-)
def next(max,current)
if current+1 == max
return 0
else
return current+1
end
end
Run Code Online (Sandbox Code Playgroud)
请注意,当代码运行时,我需要能够在我的示例0..3中随时分配任何"有效数字".
Ruby 1.8.7具有Enumerable #cycle
(0..3).cycle{|x| puts x}
Run Code Online (Sandbox Code Playgroud)
将永远循环.
我觉得这很酷:
looper = (0..3).cycle
20.times { puts looper.next }
Run Code Online (Sandbox Code Playgroud)