Skip to content

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

instance method

Array#shift

() -> Elem
(::int n) -> ::Array[Elem]
shift → object or nil
shift(count) → new_array or nil

Removes and returns leading elements from self.

With no argument, removes and returns one element, if available, or nil otherwise:

Example
a = [0, 1, 2, 3]
a.shift  # => 0
a        # => [1, 2, 3]
[].shift # => nil

With non-negative numeric argument count given, removes and returns the first count elements:

Example
a = [0, 1, 2, 3]
a.shift(2)   # => [0, 1]
a            # => [2, 3]
a.shift(1.1) # => [2]
a            # => [3]
a.shift(0)   # => []
a            # => [3]

If count is large, removes and returns all elements:

Example
a = [0, 1, 2, 3]
a.shift(50) # => [0, 1, 2, 3]
a           # => []

If self is empty, returns a new empty array.

Related: see Methods for Deleting.

See also #shelljoin #shuffle #select! #shuffle! also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0