Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
String#index
index(substring, offset = 0) → integer or nil
index(regexp, offset = 0) → integer or nil
string.c
View on GitHub ↗
static VALUE
rb_str_index_m(int argc, VALUE *argv, VALUE str)
{
VALUE sub;
VALUE initpos;
rb_encoding *enc = STR_ENC_GET(str);
long pos;
if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
long slen = str_strlen(str, enc); /* str's enc */
pos = NUM2LONG(initpos);
if (pos < 0 ? (pos += slen) < 0 : pos > slen) {
if (RB_TYPE_P(sub, T_REGEXP)) {
rb_backref_set(Qnil);
}
return Qnil;
}
}
else {
pos = 0;
}
if (RB_TYPE_P(sub, T_REGEXP)) {
pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos,
enc, single_byte_optimizable(str));
if (rb_reg_search(sub, str, pos, 0) >= 0) {
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);
if (pos >= 0) {
pos = rb_str_sublen(str, pos);
return LONG2NUM(pos);
}
}
return Qnil;
}
Returns the integer index of the first match for the given argument, or nil if none found; the search of self is forward, and begins at position offset (in characters).
With string argument substring, returns the index of the first matching substring in self:
Example
'foo'.index('f') # => 0 'foo'.index('o') # => 1 'foo'.index('oo') # => 1 'foo'.index('ooo') # => nil 'тест'.index('с') # => 2 'こんにちは'.index('ち') # => 3
With Regexp argument regexp, returns the index of the first match in self:
Example
'foo'.index(/o./) # => 1 'foo'.index(/.o/) # => 0
With positive integer offset, begins the search at position offset:
Example
'foo'.index('o', 1) # => 1 'foo'.index('o', 2) # => 2 'foo'.index('o', 3) # => nil 'тест'.index('с', 1) # => 2 'こんにちは'.index('ち', 2) # => 3
With negative integer offset, selects the search position by counting backward from the end of self:
Example
'foo'.index('o', -1) # => 2 'foo'.index('o', -2) # => 1 'foo'.index('o', -3) # => 1 'foo'.index('o', -4) # => nil 'foo'.index(/o./, -2) # => 1 'foo'.index(/.o/, -2) # => 1
Related: String#rindex.