Say I have an array of size
5. I want to take an index (from 0-4) as input, and iterate through the array, starting at the supplied index.
For example, if the index given was 3, I want to iterate like so:
arr[3]
arr[4]
arr[0]
arr[1]
arr[2]
I can think of plenty of ways to do this - but what's the Ruby way to do it?
You can use Array#rotate
from version 1.9.2
[4,3,6,7,8].rotate(2).each{|i|print i}
67843
There's plenty of ways to do it in ruby I should imagine. Not sure what the ruby way to do it. Maybe:
arr.size.times do |i|
puts arr.at((3 + i).modulo(arr.size))
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With