instance method
String#index
(::Regexp | ::string pattern, ?::int offset) -> ::Integer?
index(pattern, 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 position of the first substring that matches the given argument pattern, or nil if none found.
When pattern is a string, 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 # Characters, not bytes. 'こんにちは'.index('ち') # => 3
When pattern is a Regexp, returns the index of the first match in self:
Example
'foo'.index(/o./) # => 1 'foo'.index(/.o/) # => 0
When offset is non-negative, begins the search at position offset; the returned index is relative to the beginning of self:
Example
'bar'.index('r', 0) # => 2 'bar'.index('r', 1) # => 2 'bar'.index('r', 2) # => 2 'bar'.index('r', 3) # => nil 'bar'.index(/[r-z]/, 0) # => 2 'тест'.index('с', 1) # => 2 'тест'.index('с', 2) # => 2 'тест'.index('с', 3) # => nil # Offset in characters, not bytes. 'こんにちは'.index('ち', 2) # => 3
With negative integer argument 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: see Querying.