Skip to content

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

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

Removes and returns the substring of self specified by the arguments. See String Slices.

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.3 · 3.2 · 3.1 · 3.0