I have an interval let's say (0..3) where next element is +1 unless the last. Then the next is 0. I solved it by the code below. Just wondering if there is anything else outhere :-)
我有一个区间(0.. .3)下一个元素是+1除非是最后一个元素。然后下一个是0。我用下面的代码解决了这个问题。我想知道还有什么其他的吗?
def next(max,current)
if current+1 == max
return 0
else
return current+1
end
end
EDIT
please note that when the code runs I need to be able to assign any 'valid number' in my example 0..3 at any time.
请注意,当代码运行时,我需要能够在示例0中分配任何“有效数字”。3在任何时间。
2 个解决方案
#1
6
Ruby 1.8.7 has Enumerable#cycle
Ruby 1.8.7可列举的#循环
(0..3).cycle{|x| puts x}
will cycle forever.
永远循环。
I think this is really cool:
我觉得这真的很酷:
looper = (0..3).cycle
20.times { puts looper.next }
#2
3
How about:
如何:
def next(max,current)
(current+1) % max
end
Should work unless max==0
, but you could easily catch that and bail. :)
应该是有效的,除非max= 0,但你可以很容易地抓住它并保释。:)
Happy coding!
编码快乐!
Edit: You should also be aware that next
is a reserved keyword (see this overview), it'd be wise to choose another name for your method..
编辑:你也应该知道next是一个保留的关键字(见这个概述),为你的方法选择另一个名字是明智的。
#1
6
Ruby 1.8.7 has Enumerable#cycle
Ruby 1.8.7可列举的#循环
(0..3).cycle{|x| puts x}
will cycle forever.
永远循环。
I think this is really cool:
我觉得这真的很酷:
looper = (0..3).cycle
20.times { puts looper.next }
#2
3
How about:
如何:
def next(max,current)
(current+1) % max
end
Should work unless max==0
, but you could easily catch that and bail. :)
应该是有效的,除非max= 0,但你可以很容易地抓住它并保释。:)
Happy coding!
编码快乐!
Edit: You should also be aware that next
is a reserved keyword (see this overview), it'd be wise to choose another name for your method..
编辑:你也应该知道next是一个保留的关键字(见这个概述),为你的方法选择另一个名字是明智的。