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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With