Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#rindex

rindex(substring, offset = self.length) → integer or nil
rindex(regexp, offset = self.length) → integer or nil

Returns the Integer index of the last occurrence of the given substring, or nil if none found:

Example
'foo'.rindex('f') # => 0
'foo'.rindex('o') # => 2
'foo'.rindex('oo') # => 1
'foo'.rindex('ooo') # => nil

Returns the Integer index of the last match for the given Regexp regexp, or nil if none found:

Example
'foo'.rindex(/f/) # => 0
'foo'.rindex(/o/) # => 2
'foo'.rindex(/oo/) # => 1
'foo'.rindex(/ooo/) # => nil

The last match means starting at the possible last position, not the last of longest matches.

Example
'foo'.rindex(/o+/) # => 2
$~ #=> #<MatchData "o">

To get the last longest match, needs to combine with negative lookbehind.

Example
'foo'.rindex(/(?<!o)o+/) # => 1
$~ #=> #<MatchData "oo">

Or String#index with negative lookforward.

Example
'foo'.index(/o+(?!.*o)/) # => 1
$~ #=> #<MatchData "oo">

Integer argument offset, if given and non-negative, specifies the maximum starting position in the

Example
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

If offset is a negative Integer, the maximum starting position in the string to end the search is the sum of the string’s length and offset:

Example
'foo'.rindex('o', -1) # => 2
'foo'.rindex('o', -2) # => 1
'foo'.rindex('o', -3) # => nil
'foo'.rindex('o', -4) # => nil

Related: String#index.

See also #reverse! #rjust #reverse #rpartition also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0