Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#rotate

(?::int count) -> ::Array[Elem]
rotate(count = 1) → new_array

Returns a new array formed from self with elements rotated from one end to the other.

With non-negative numeric count, rotates elements from the beginning to the end:

Example
[0, 1, 2, 3].rotate(2)   # => [2, 3, 0, 1]
[0, 1, 2, 3].rotate(2.1) # => [2, 3, 0, 1]

If count is large, uses count % array.size as the count:

Example
[0, 1, 2, 3].rotate(22) # => [2, 3, 0, 1]

With a count of zero, rotates no elements:

Example
[0, 1, 2, 3].rotate(0) # => [0, 1, 2, 3]

With negative numeric count, rotates in the opposite direction, from the end to the beginning:

Example
[0, 1, 2, 3].rotate(-1) # => [3, 0, 1, 2]

If count is small (far from zero), uses count % array.size as the count:

Example
[0, 1, 2, 3].rotate(-21) # => [3, 0, 1, 2]

Related: see Methods for Fetching.

See also #rotate! #rindex #reverse_each #sample also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0