What is array.rotate() in Ruby?
array.rotate(count) is an array method in Ruby. This method rotates an array so that the element at position count or at count index becomes the first element of the new array.
The count here represents an integer, which could be positive or negative.
Syntax
array.rotate(count)
Parameter
count: This is a positive or negative integer that specifies the element at thecountposition that should begin the rotated array.
Return value
A new array is returned after the array has been rotated so that the element at count is the first element of the new array.
Code
In the below code, we create some arrays and apply the rotate() method on them along with some count parameters.
# create arraysarray1 = [1, 2, 3, 4, 5]array2 = ["a", "b", "c", "d", "e"]array3 = ["Python", "Ruby", "Java"]array4 = [true, false, nil, 0, 1]# rotate arraysa = array1.rotate(2) # rotate from element 3b = array2.rotate(4) # rotate from element 5c = array3.rotate(1) # rotate from element 2d = array4.rotate(3) # rotate from element 4# print rotated arraysputs "rotated form = #{a}"puts "rotated form = #{b}"puts "rotated form = #{c}"puts "rotated form = #{d}"
rotate() without a parameter
When no parameter is passed to the rotate() function, 1 is taken as the count.
Let’s find out what happens when the rotate() method receives no parameter.
# create an arrayarray = [1, 2, 3, 4, 5]# rotate an arraya = array.rotate() # [2, 3, 4, 5, 1]# print rotated arrayputs "#{array} rotated = #{a}"
In the above code, the array was rotated at count = 1.
rotate() with a negative count
When a negative count is passed to the rotate() method, say , etc., then it rotates in the opposite direction, starting from the end of self where is the last element.
See the example below:
# create arrayarray = [1, 2, 3, 4, 5]# rotate arraya = array.rotate(-2) # [4, 5, 1, 2, 3]# print rotated arrayputs "#{array} rotated = #{a}"