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#shift

array.shift → object or nil
array.shift(n) → new_array

Removes and returns leading elements.

When no argument is given, removes and returns the first element:

Example
a = [:foo, 'bar', 2]
a.shift # => :foo
a # => ['bar', 2]

Returns nil if self is empty.

When positive Integer argument n is given, removes the first n elements; returns those elements in a new Array:

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

If n is as large as or larger than self.length, removes all elements; returns those elements in a new Array:

Example
a = [:foo, 'bar', 2]
a.shift(3) # => [:foo, 'bar', 2]

If n is zero, returns a new empty Array; self is unmodified.

Related: push, pop, unshift.

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