Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.rotate() in Ruby?

okwudili onyejiaku

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 the count position 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 arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["Python", "Ruby", "Java"]
array4 = [true, false, nil, 0, 1]

# rotate arrays
a = array1.rotate(2) # rotate from element 3
b = array2.rotate(4) # rotate from element 5
c = array3.rotate(1) # rotate from element 2
d = array4.rotate(3) # rotate from element 4

# print rotated arrays
puts "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 array
array = [1, 2, 3, 4, 5]

# rotate an array
a = array.rotate() # [2, 3, 4, 5, 1]

# print rotated array
puts "#{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 1,19,2-1, -19, -2, etc., then it rotates in the opposite direction, starting from the end of self where 1-1 is the last element.

See the example below:

# create array
array =  [1, 2, 3, 4, 5]

# rotate array
a = array.rotate(-2) # [4, 5, 1, 2, 3]

# print rotated array
puts "#{array} rotated = #{a}"

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring