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#slice!

array.slice!(n) → object or nil
array.slice!(start, length) → new_array or nil
array.slice!(range) → new_array or nil

Removes and returns elements from self.

When the only argument is an Integer n, removes and returns the nth element in self:

Example
a = [:foo, 'bar', 2]
a.slice!(1) # => "bar"
a # => [:foo, 2]

If n is negative, counts backwards from the end of self:

Example
a = [:foo, 'bar', 2]
a.slice!(-1) # => 2
a # => [:foo, "bar"]

If n is out of range, returns nil.

When the only arguments are Integers start and length, removes length elements from self beginning at offset start; returns the deleted objects in a new Array:

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

If start + length exceeds the array size, removes and returns all elements from offset start to the end:

Example
a = [:foo, 'bar', 2]
a.slice!(1, 50) # => ["bar", 2]
a # => [:foo]

If start == a.size and length is non-negative, returns a new empty Array.

If length is negative, returns nil.

When the only argument is a Range object range, treats range.min as start above and range.size as length above:

Example
a = [:foo, 'bar', 2]
 a.slice!(1..2) # => ["bar", 2]
a # => [:foo]

If range.start == a.size, returns a new empty Array.

If range.start is larger than the array size, returns nil.

If range.end is negative, counts backwards from the end of the array:

Example
a = [:foo, 'bar', 2]
a.slice!(0..-2) # => [:foo, "bar"]
a # => [2]

If range.start is negative, calculates the start index backwards from the end of the array:

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

Ruby version changes

  1. 3.0
See also #slice #sort #size #sort! also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1