Skip to content

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

instance method

String#insert

insert(index, other_string) → self

Inserts the given other_string into self; returns self.

If the Integer index is positive, inserts other_string at offset index:

Example
'foo'.insert(1, 'bar') # => "fbaroo"

If the Integer index is negative, counts backward from the end of self and inserts other_string at offset index+1 (that is, after self[index]):

Example
'foo'.insert(-2, 'bar') # => "fobaro"
See also #initialize_copy #inspect #index #intern also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0