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 :-)
def next(max,current)
if current+1 == max
return 0
else
return curr开发者_运维技巧ent+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.
Ruby 1.8.7 has Enumerable#cycle
(0..3).cycle{|x| puts x}
will cycle forever.
I think this is really cool:
looper = (0..3).cycle
20.times { puts looper.next }
How about:
def next(max,current)
(current+1) % max
end
Should work unless max==0
, but you could easily catch that and bail. :)
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..
精彩评论