What is the "Ruby way" for iterating over an array - from array [n] to array [n - 1]?

Let's 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 with the index set.

For example, if the pointer was 3, I want to repeat it like this:

 arr[3] arr[4] arr[0] arr[1] arr[2] 

I can think of many ways to do this, but what kind of Ruby is this?

+6
arrays ruby iteration
source share
3 answers

You can use Array#rotate from version 1.9.2

  [4,3,6,7,8].rotate(2).each{|i|print i} 67843 
+14
source share

There are many ways to do this in ruby. You do not know what the ruby ​​method is. May be:

 arr.size.times do |i| puts arr.at((3 + i).modulo(arr.size)) end 
+1
source share

Given your index: i:

 (arr.from(i) + arr[0,i]).each 
0
source share

All Articles