tags:

views:

104

answers:

2

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

+2  A: 

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

AdrianoKF
hehe, you got there before me :P
JP
+6  A: 

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 }
steenslag
It’s a method of `Enumerable`, actually, so `.to_a` is not needed.
jleedev
Thanks! Code corrected.
steenslag
@steenslag: sometimes I need to start with value different to 0. But `looper = (0..3).cycle` is still what I want to cycle. Is that possible?
Radek