Take the 2-minute tour ×

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:


I can think of plenty of ways to do this - but what's the Ruby way to do it?

share|improve this question
add comment

3 Answers

up vote 13 down vote accepted

You can use Array#rotate from version 1.9.2

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

share|improve this answer
+1 for using built-ins –  Joseph Weissman Sep 8 '10 at 23:05
This is amazing. –  Justin L. Sep 8 '10 at 23:41
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 Sep 8 '10 at 23:56
add comment

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))
share|improve this answer
I don't think, that using indexes is Ruby-way. –  Nakilon Sep 8 '10 at 23:02
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 Sep 8 '10 at 23:12
add comment

Given your index is i:

(arr.from(i) + arr[0,i]).each
share|improve this answer
WTF from? _Oo –  Nakilon Jan 7 '11 at 14:57
add comment

Your Answer


