Method: String#insert

Defined in:
string.c

#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:

'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]):

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

Returns:

  • (self)
[View source]

4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
# File 'string.c', line 4991

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_splice(str, pos, 0, str2);
    return str;
}