Method: String#index
- Defined in:
- string.c
#index(substring, offset = 0) ⇒ Integer? #index(regexp, offset = 0) ⇒ Integer?
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
3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 |
# File 'string.c', line 3691
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);
}
|