String#rindex
static VALUE
rb_str_rindex_m(int argc, VALUE *argv, VALUE str)
{
VALUE sub;
VALUE initpos;
rb_encoding *enc = STR_ENC_GET(str);
long pos, len = str_strlen(str, enc); /* str's enc */
if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
pos = NUM2LONG(initpos);
if (pos < 0 && (pos += len) < 0) {
if (RB_TYPE_P(sub, T_REGEXP)) {
rb_backref_set(Qnil);
}
return Qnil;
}
if (pos > len) pos = len;
}
else {
pos = len;
}
if (RB_TYPE_P(sub, T_REGEXP)) {
/* enc = rb_enc_check(str, sub); */
pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos,
enc, single_byte_optimizable(str));
if (rb_reg_search(sub, str, pos, 1) >= 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_rindex(str, sub, pos);
if (pos >= 0) {
pos = rb_str_sublen(str, pos);
return LONG2NUM(pos);
}
}
return Qnil;
}
Returns the integer position of the last substring that matches the given argument pattern, or nil if none found.
When pattern is a string, returns the index of the last matching substring in self:
'foo'.rindex('f') # => 0
'foo'.rindex('o') # => 2
'foo'.rindex('oo' # => 1
'foo'.rindex('ooo') # => nil
'тест'.rindex('т') # => 3
'こんにちは'.rindex('ち') # => 3
When pattern is a Regexp, returns the index of the last match in self:
'foo'.rindex(/f/) # => 0 'foo'.rindex(/o/) # => 2 'foo'.rindex(/oo/) # => 1 'foo'.rindex(/ooo/) # => nil
When offset is non-negative, it specifies the maximum starting position in the string to end the search:
'foo'.rindex('o', 0) # => nil 'foo'.rindex('o', 1) # => 1 'foo'.rindex('o', 2) # => 2 'foo'.rindex('o', 3) # => 2
With negative integer argument offset, selects the search position by counting backward from the end of self:
'foo'.rindex('o', -1) # => 2 'foo'.rindex('o', -2) # => 1 'foo'.rindex('o', -3) # => nil 'foo'.rindex('o', -4) # => nil
The last match means starting at the possible last position, not the last of longest matches:
'foo'.rindex(/o+/) # => 2 $~ # => #<MatchData "o">
To get the last longest match, combine with negative lookbehind:
'foo'.rindex(/(?<!o)o+/) # => 1 $~ # => #<MatchData "oo">
Or String#index with negative lookforward.
'foo'.index(/o+(?!.*o)/) # => 1 $~ # => #<MatchData "oo">
Related: see Querying.