nfm
nfm

Reputation: 20667

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?

Upvotes: 6

Views: 679

Answers (3)

Nakilon
Nakilon

Reputation: 35054

You can use Array#rotate from version 1.9.2

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

 67843

Upvotes: 14

jordinl
jordinl

Reputation: 5239

Given your index is i:

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

Upvotes: 0

Shadwell
Shadwell

Reputation: 34774

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

Upvotes: 1

Related Questions