Array#rotate

Added in v1.9.2 · Updated March 13, 2026 · Array Methods
ruby array rotate

.rotate and .rotate! shift array elements by moving the element at a given index to the front, wrapping elements from the beginning to the end.

Brief Intro

rotate creates a new array with elements rearranged. rotate! modifies the original array in place. Both methods are useful for cycling through queue-like data structures or creating rotating schedules.

Signature

MethodParametersReturn Type
rotatecnt = 1 (Integer)Array
rotate!cnt = 1 (Integer)Array (self)

Parameter Details:

  • cnt — The zero-based index of the element that should become the first element. Default is 1. Negative counts rotate in the opposite direction.

Code Examples

Basic Rotation

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

array.rotate
# => [2, 3, 4, 5, 1]

array
# => [1, 2, 3, 4, 5]  (original unchanged)

Rotate with Custom Count

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

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

array.rotate(0)
# => [1, 2, 3, 4, 5]  (no rotation)

array.rotate(5)
# => [1, 2, 3, 4, 5]  (full cycle)

Negative Rotation

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

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

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

In-Place Rotation with rotate!

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

array.rotate!
# => [2, 3, 4, 5, 1]

array
# => [2, 3, 4, 5, 1]  (original modified)

array.rotate!(3)
# => [5, 1, 2, 3, 4]

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

Practical Use: Round-Robin Scheduling

players = ["Alice", "Bob", "Charlie", "Diana"]

# Generate schedule for 4 rounds
4.times do |round|
  puts "Round #{round + 1}: #{players.join(' vs ')}"
  players.rotate!
end

# Output:
# Round 1: Alice vs Bob vs Charlie vs Diana
# Round 2: Bob vs Charlie vs Diana vs Alice
# Round 3: Charlie vs Diana vs Alice vs Bob
# Round 4: Diana vs Alice vs Bob vs Charlie

Return Value

  • rotate returns a new array containing the rotated elements. The original array remains unchanged.
  • rotate! returns self (the modified array), allowing method chaining.
  • When cnt equals the array length, the returned array equals the original.

Edge Cases

  • Empty array returns a new empty array.
  • Single-element array returns itself (new array for rotate, same for rotate!).
[].rotate
# => []

[].rotate!
# => []

[42].rotate
# => [42]

[42].rotate!
# => [42]

See Also