Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
String#insert
insert(index, other_string) → self
string.c
View on GitHub ↗
static VALUE
rb_str_insert(VALUE str, VALUE idx, VALUE str2)
{
long pos = NUM2LONG(idx);
if (pos == -1) {
return rb_str_append(str, str2);
}
else if (pos < 0) {
pos++;
}
rb_str_update(str, pos, 0, str2);
return str;
}
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"