Is there a more Ruby-ish and cleaner way to get a number to operate within a range. If it hits the upper bound, the next number should be 1 again. Often seen in algorythms that e.g. force month 16 and 28 to be April (16-12=4).
The case: I have twelve images and N questions. Each question gets the next image, if all images are “used”, it should re-start at image 1.
def image_rotation(number) {
uplim = 12
return number if number <= uplim
return image_rotation(number - uplim) if number > uplim
}
questions.each_with_index do |q,i|
img = File::join("images", "image-#{image_rotation(i+1)}.jpg")
end
Note: I am not familiar with the terminology of this (kind of) problem, so searching stackoverflow did not give me any results or hints; but I cannot believe this question is not a duplicate, yet. Please point me to a keyword, answer/duplicate or feel free to answer it 🙂
And Bonuspoints for a one-liner. I need this in an ERB-file, so if I can keep the code clean, clear and simple, then I prefer to have it solved there, entirely.
Use modulo (
%):If that’s all your method does, though, you could just do: