Skip to content
instance method

String#slice!

(::int index, ?::int length) -> ::String?
(::range[::int?] range) -> ::String?
(::String substring) -> ::String?
(::Regexp regexp, ?::MatchData::capture backref) -> ::String?
slice!(index) → new_string or nil
slice!(start, length) → new_string or nil
slice!(range) → new_string or nil
slice!(regexp, capture = 0) → new_string or nil
slice!(substring) → new_string or nil

Like String#[] (and its alias String#slice), except that:

  • Performs substitutions in self (not in a copy of self).

  • Returns the removed substring if any modifications were made, nil otherwise.

A few examples:

Example
s = 'hello'
s.slice!('e') # => "e"
s             # => "hllo"
s.slice!('e') # => nil
s             # => "hllo"

Related: see Modifying.

Ruby version changes

  1. 3.0
See also #slice #split #size #squeeze also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0