Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
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"
 
               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;
}
            

Was this page useful?