Skip to main content

Ruby rotate array method

In ruby programming language, rotate() array methods are used to rotate the array elements in backward and forward direction. By default this method are rotate array in forward direction and returning resulting new array. Syntax of this method as follows.

rotate(count=1) → new array

This method is accept a parameter object, This parameter value is optional, by default it is initialized with of 1.

Ruby rotate() method example

This method accept numbers objects, positive number indicates forward rotation, and negative numbers indicate backward rotation. And number is indicates number of rotation. Let see an example.

# Our array
record  = [7,6,5,4,3,2,1]

# rotate array
r1 = record.rotate
r2 = record.rotate(1)
r3 = record.rotate(3)

# Display record
print(" Record : ", record)

# Display result
print("\n r1 : ",r1) 
print("\n r2 : ",r2) 
print("\n r3 : ",r3) 
Ruby rotate method example 1
 Record : [7, 6, 5, 4, 3, 2, 1]
 r1 : [6, 5, 4, 3, 2, 1, 7]
 r2 : [6, 5, 4, 3, 2, 1, 7]
 r3 : [4, 3, 2, 1, 7, 6, 5]

By default this method are rotate single element, In above example record.rotate(3) indicates rotate 3 elements. Similar when its provide negative number as parameter, Then it will work on backward direction. For example.

# Our array
record  = [7,6,5,4,3,2,1]

# rotate array
r1 = record.rotate(-2)
r2 = record.rotate(-3)

# Display record
print(" Record : ", record)

# Display result
print("\n r1 : ",r1) 
print("\n r2 : ",r2) 
Ruby rotate method example 2
 Record : [7, 6, 5, 4, 3, 2, 1]
 r1 : [2, 1, 7, 6, 5, 4, 3]
 r2 : [3, 2, 1, 7, 6, 5, 4]

When array contains custom objects and specific collection in this situation inner element of array is shareable.

# Our array
record  = [1,['a','b'],false]

# rotate array
r1 = record.rotate(-2)
r2 = record.rotate( 2)

# Display record
print(" Record : ", record)

# Display result
print("\n r1 : ",r1) 
print("\n r2 : ",r2) 
Ruby rotate method example 3
 Record : [1, ["a", "b"], false]
 r1 : [["a", "b"], false, 1]
 r2 : [false, 1, ["a", "b"]]




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment