Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

String#insert

(::int index, ::string other_str) -> self
insert(offset, other_string) → self

Inserts the given other_string into self; returns self.

If the given index is non-negative, inserts other_string at offset index:

Example
'foo'.insert(0, 'bar')       # => "barfoo"
'foo'.insert(1, 'bar')       # => "fbaroo"
'foo'.insert(3, 'bar')       # => "foobar"
'こんにちは'.insert(2, 'bar') # => "こんbarにちは"

If the index is negative, counts backward from the end of self and inserts other_string after the offset:

Example
'foo'.insert(-2, 'bar') # => "fobaro"

Related: see Modifying.

See also #initialize_copy #inspect #index #intern also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0