Skip to content

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

instance method

String#[]=

string[index] = new_string
string[start, length] = new_string
string[range] = new_string
string[regexp, capture = 0] = new_string
string[substring] = new_string

Replaces all, some, or none of the contents of self; returns new_string. See String Slices.

A few examples:

Example
s = 'foo'
s[2] = 'rtune'     # => "rtune"
s                  # => "fortune"
s[1, 5] = 'init'   # => "init"
s                  # => "finite"
s[3..4] = 'al'     # => "al"
s                  # => "finale"
s[/e$/] = 'ly'     # => "ly"
s                  # => "finally"
s['lly'] = 'ncial' # => "ncial"
s                  # => "financial"

String#slice is an alias for String#[].

See also #[] #ascii_only? #=~ #b also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0