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
string.c
View on GitHub ↗
static VALUE
rb_str_insert(VALUE str, VALUE idx, VALUE str2)
{
rb_len_t pos = NUM2LEN(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にちは"
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.