Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the 'Ruby way' to iterate over an array - from array[n] to array[n - 1]?

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?

like image 405
nfm Avatar asked Sep 08 '10 22:09

nfm


2 Answers

You can use Array#rotate from version 1.9.2

 [4,3,6,7,8].rotate(2).each{|i|print i}

 67843
like image 85
Nakilon Avatar answered Nov 11 '22 12:11

Nakilon


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
like image 20
Shadwell Avatar answered Nov 11 '22 12:11

Shadwell