Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#slice!

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

Removes the substring of self specified by the arguments; returns the removed substring.

See String#[] for details about the arguments that specify the substring.

A few examples:

Example
string = "This is a string"
string.slice!(2)        #=> "i"
string.slice!(3..6)     #=> " is "
string.slice!(/s.*t/)   #=> "sa st"
string.slice!("r")      #=> "r"
string                  #=> "Thing"

Ruby version changes

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