instance method
String#insert
(::int index, ::string other_str) -> self
insert(offset, 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 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ст" # Characters, not bytes. 'こんにちは'.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.