Skip to content

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

instance method

String#[]=

[T < ::_ToStr] (::int index, T replacement) -> T
[T < ::_ToStr] (::int start, ::int length, T replacement) -> T
[T < ::_ToStr] (::range[::int?] range, T replacement) -> T
[T < ::_ToStr] (::Regexp regexp, T replacement) -> T
[T < ::_ToStr] (::Regexp regexp, ::MatchData::capture backref, T replacement) -> T
[T < ::_ToStr] (::String substring, T replacement) -> T
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"
See also #[] #append_as_bytes #=~ #ascii_only? also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0