Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns the Integer index of the first occurrence of the given substring, or nil if none found:
'foo'.index('f') # => 0
'foo'.index('o') # => 1
'foo'.index('oo') # => 1
'foo'.index('ooo') # => nil
Returns the Integer index of the first match for the given Regexp regexp, or nil if none found:
'foo'.index(/f/) # => 0
'foo'.index(/o/) # => 1
'foo'.index(/oo/) # => 1
'foo'.index(/ooo/) # => nil
Integer argument offset, if given, specifies the position in the string to begin the search:
'foo'.index('o', 1) # => 1
'foo'.index('o', 2) # => 2
'foo'.index('o', 3) # => nil
If offset is negative, counts backward from the end of self:
'foo'.index('o', -1) # => 2
'foo'.index('o', -2) # => 1
'foo'.index('o', -3) # => 1
'foo'.index('o', -4) # => nil
Related: String#rindex.
 
               static VALUE
rb_str_index_m(int argc, VALUE *argv, VALUE str)
{
    VALUE sub;
    VALUE initpos;
    long pos;

    if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
        pos = NUM2LONG(initpos);
    }
    else {
        pos = 0;
    }
    if (pos < 0) {
        pos += str_strlen(str, NULL);
        if (pos < 0) {
            if (RB_TYPE_P(sub, T_REGEXP)) {
                rb_backref_set(Qnil);
            }
            return Qnil;
        }
    }

    if (RB_TYPE_P(sub, T_REGEXP)) {
        if (pos > str_strlen(str, NULL))
            return Qnil;
        pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos,
                         rb_enc_check(str, sub), single_byte_optimizable(str));

        if (rb_reg_search(sub, str, pos, 0) < 0) {
            return Qnil;
        }
        else {
            VALUE match = rb_backref_get();
            struct re_registers *regs = RMATCH_REGS(match);
            pos = rb_str_sublen(str, BEG(0));
            return LONG2NUM(pos);
        }
    }
    else {
        StringValue(sub);
        pos = rb_str_index(str, sub, pos);
        pos = rb_str_sublen(str, pos);
    }

    if (pos == -1) return Qnil;
    return LONG2NUM(pos);
}
            

Was this page useful?