Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby method to cycle array to the right

Is there a ruby method that will cycle every element in an array to the right by a specific number?

For example, if it takes in the array [1,2,3,4] and the shift number 1, returns [4,1,2,3].
Or if it takes in the array [1,2,3,4,5] and the shift number 2, returns [4,5,1,2,3].

I could make the method myself, but ruby usually already has a method for this type of thing. I'm having trouble finding it since I don't know what it would be called. The array methods cycle and shift do not have this behavior.

like image 886
Christian Doucette Avatar asked Sep 25 '26 14:09

Christian Doucette


1 Answers

You can use rotate method which does similar things

2.6.5 :012 > arr = [1,2,3,4]
 => [1, 2, 3, 4]
2.6.5 :013 > arr.rotate
 => [2, 3, 4, 1]
2.6.5 :014 > arr = [1,2,3,4,5]
 => [1, 2, 3, 4, 5]
2.6.5 :015 > arr.rotate(2)
 => [3, 4, 5, 1, 2]

For Ex :-

2.6.5 :021 > def array_rotation(array, shift = 1)
2.6.5 :022?>     array.rotate(- shift)
2.6.5 :023?>   end
 => :array_rotation
2.6.5 :024 > arr = [1,2,3,4,5]
 => [1, 2, 3, 4, 5]
2.6.5 :025 > array_rotation arr, 2
 => [4, 5, 1, 2, 3]
2.6.5 :026 > arr = [1,2,3,4]
 => [1, 2, 3, 4]
2.6.5 :027 > array_rotation arr, 1
 => [4, 1, 2, 3]
like image 166
Salil Avatar answered Sep 28 '26 03:09

Salil