Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#rotate

array.rotate → new_array
array.rotate(count) → new_array

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

When no argument given, returns a new Array that is like self, except that the first element has been rotated to the last position:

Example
a = [:foo, 'bar', 2, 'bar']
a1 = a.rotate
a1 # => ["bar", 2, "bar", :foo]

When given a non-negative Integer count, returns a new Array with count elements rotated from the beginning to the end:

Example
a = [:foo, 'bar', 2]
a1 = a.rotate(2)
a1 # => [2, :foo, "bar"]

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

Example
a = [:foo, 'bar', 2]
a1 = a.rotate(20)
a1 # => [2, :foo, "bar"]

If count is zero, returns a copy of self, unmodified:

Example
a = [:foo, 'bar', 2]
a1 = a.rotate(0)
a1 # => [:foo, "bar", 2]

When given a negative Integer count, rotates in the opposite direction, from end to beginning:

Example
a = [:foo, 'bar', 2]
a1 = a.rotate(-2)
a1 # => ["bar", 2, :foo]

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

Example
a = [:foo, 'bar', 2]
a1 = a.rotate(-5)
a1 # => ["bar", 2, :foo]
See also #rotate! #rindex #reverse_each #sample also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1