String.index / rindex
Methods that search a string for a substring and return the position (index) of the first or last match.
Syntax
# Returns the position of the first match. string.index(search_string) string.index(search_string, start_position) # Returns the position of the last match. string.rindex(search_string) string.rindex(search_string, end_position)
Method List
| Method | Description |
|---|---|
| index(str) | Returns the position of the first match in the string as an integer. Returns nil if not found. |
| index(str, pos) | Starts the search from the position given as the second argument. A negative value counts from the end of the string. |
| rindex(str) | Searches from the end of the string and returns the position of the last match. Returns nil if not found. |
| rindex(str, pos) | Searches backward from the position given as the second argument. |
Sample Code
text = "abcabc"
# Get the position of the first match.
puts text.index("b") # 1
puts text.index("b", 2) # 4 (searches from index 2 onward)
# Get the position of the last match.
puts text.rindex("b") # 4
puts text.rindex("b", 3) # 1 (searches up to index 3)
# Returns nil if not found.
puts text.index("z").inspect # nil
# Works with multibyte strings.
message = "hello, good evening"
puts message.index("o") # 4
puts message.rindex("o") # 10
# Example combining with a nil check.
path = "/home/user/documents/file.txt"
slash_pos = path.rindex("/")
if slash_pos
filename = path[slash_pos + 1..]
puts filename # file.txt
end
Overview
index searches from the beginning of the string and returns the position of the first match. rindex searches from the end and returns the position of the last match. Positions are zero-based. Because the return value is nil when no match is found, it is recommended to check for nil before using the result.
You can also pass a regular expression as the argument (e.g., index(/[0-9]/)). These methods are commonly used in string processing tasks such as finding the last / in a file path to extract the filename or extension.
To extract a portion of a string, use slice / []. To simply check whether a substring exists, use include?.
If you find any errors or copyright issues, please contact us.