Skip to content

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

instance method

Array#slice!

(::int index) -> Elem
(::int start, ::int length) -> ::Array[Elem]?
(::Range[::Integer] range) -> ::Array[Elem]?
slice!(index) → object or nil
slice!(start, length) → new_array or nil
slice!(range) → new_array or nil

Removes and returns elements from self.

With numeric argument index given, removes and returns the element at offset index:

Example
a = ['a', 'b', 'c', 'd']
a.slice!(2)   # => "c"
a             # => ["a", "b", "d"]
a.slice!(2.1) # => "d"
a             # => ["a", "b"]

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

Example
a = ['a', 'b', 'c', 'd']
a.slice!(-2) # => "c"
a            # => ["a", "b", "d"]

If index is out of range, returns nil.

With numeric arguments start and length given, removes length elements from self beginning at zero-based offset start; returns the removed objects in a new array:

Example
a = ['a', 'b', 'c', 'd']
a.slice!(1, 2)     # => ["b", "c"]
a                  # => ["a", "d"]
a.slice!(0.1, 1.1) # => ["a"]
a                  # => ["d"]

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

Example
a = ['a', 'b', 'c', 'd']
a.slice!(-2, 1) # => ["c"]
a               # => ["a", "b", "d"]

If start is out-of-range, returns nil:

Example
a = ['a', 'b', 'c', 'd']
a.slice!(5, 1)  # => nil
a.slice!(-5, 1) # => nil

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

Example
a = ['a', 'b', 'c', 'd']
a.slice!(2, 50) # => ["c", "d"]
a               # => ["a", "b"]

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

If length is negative, returns nil.

With Range argument range given, treats range.min as start (as above) and range.size as length (as above):

Example
a = ['a', 'b', 'c', 'd']
a.slice!(1..2) # => ["b", "c"]
a              # => ["a", "d"]

If range.start == a.size, returns a new empty array:

Example
a = ['a', 'b', 'c', 'd']
a.slice!(4..5) # => []

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

Example
a = ['a', 'b', 'c', 'd']
a.slice!(5..6) # => nil

If range.start is negative, calculates the start index by counting backwards from the end of self:

Example
a = ['a', 'b', 'c', 'd']
a.slice!(-2..2) # => ["c"]

If range.end is negative, calculates the end index by counting backwards from the end of self:

Example
a = ['a', 'b', 'c', 'd']
a.slice!(0..-2) # => ["a", "b", "c"]

Related: see Methods for Deleting.

Ruby version changes

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