views:

82

answers:

3

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?

+1  A: 

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
Shadwell
I don't think, that using indexes is Ruby-way.
Nakilon
Fair enough, my point was more that there are many ways to do it rather than it being possible to provide a definitive answer.
Shadwell
A: 

Given your index is i:

(arr.from(i) + arr[0,i]).each
jordinl
+10  A: 

You can use Array#rotate from version 1.9.2

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

 67843
Nakilon
+1 for using built-ins
Joe
This is amazing.
Justin L.
Heh, I knew there'd be a nice way to do it :) Can't believe I missed 1.9.2 being released as well!!
nfm