Next item (current + 1) or 0 (ruby)

I have a let say interval (0..3) where the next element is +1 if only the last one. Then the next one is 0. I solved it with the code below. Just wondering if there is anything else :-)

def next(max,current)

if current+1 == max
  return 0
else
  return current+1
end  
end

      

EDIT

note that when running the code, I need to be able to assign any "real number" in my example 0..3 at any time.

+2


source to share


2 answers


Ruby 1.8.7 has Enumerable # cycle

(0..3).cycle{|x| puts x}

      

will run cyclically.



I think this is really cool:

looper = (0..3).cycle
20.times { puts looper.next }

      

+6


source


What about:

def next(max,current)
(current+1) % max
end

      

Should work if max==0

, but you can easily catch this and bail. :)



Happy coding!

Edit: You should also know what next

is the reserved keyword (see this overview ), it would be wise to choose a different name for your method.

+3


source







All Articles