简体   繁体   中英

Cycle through an array in Ruby

I have an array of the form [1,2,3,4,5].

Is it possible to loop through this array and during each iteration get an array where the starting point is the current element and the end point is the element before that?

Like

[1,2,3,4,5]

[2,3,4,5,1]

[3,4,5,1,2]

[4,5,1,2,3]

[5,1,2,3,4]

I am trying with .cycle method of array but it is not giving the expected result.

Check out rotate .

a = [ "a", "b", "c", "d" ]
a.rotate         #=> ["b", "c", "d", "a"]
irb(main):005:0> array = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
irb(main):006:0> array.size.times.map{|i| array.rotate(i)}
=> [[1, 2, 3, 4, 5], [2, 3, 4, 5, 1], [3, 4, 5, 1, 2], [4, 5, 1, 2, 3], [5, 1, 2 , 3, 4]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM