String#rindex
str.rindex(substring [, offset]) -> integer or nil Returns:
Integer or nil · Updated March 14, 2026 · String Methods strings searching index position
The rindex method searches a string from the right side, returning the index of the last occurrence of the specified substring or pattern. Unlike index which finds the first match, rindex finds the last.
Basic Usage
# Find last occurrence
"hello".rindex("l") # => 3
"hello".rindex("x") # => nil
# First vs last
"hello".index("l") # => 2
"hello".rindex("l") # => 3
Practical Examples
File Path Operations
# Find last slash
path = "/home/user/documents/file.txt"
path.rindex("/") # => 20
# Get filename
filename = path[path.rindex("/") + 1..-1]
# => "file.txt"
Extension Extraction
filename = "archive.tar.gz"
dot_pos = filename.rindex(".")
extension = filename[dot_pos + 1..-1]
# => "gz"
Finding Last Match
text = "one two one three one"
text.rindex("one") # => 16 (last occurrence)
text.rindex("three") # => 10
With Offset
# Limit search to before position
"hello world hello".rindex("hello", 10) # => 0 (first "hello")
"hello world hello".rindex("hello") # => 13 (last "hello")
With Regex
"ababab".rindex(/b/) # => 5
"test123abc456".rindex(/\d+/) # => 10 (last digit sequence)
Return Values
# Returns index or nil
result = "hello".rindex("x")
puts result # => nil
# 0-based indexing
"abc".rindex("a") # => 0
"abc".rindex("c") # => 2
Use Cases
- Finding last occurrence
- Extracting file extensions
- Parsing paths
- Reverse string search
- Finding last delimiter
Comparison with index
text = "the quick brown fox"
text.index(" ") # => 3 (first space)
text.rindex(" ") # => 16 (last space)