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
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 to share