Index, rindex: Find StringsUse index and rindex to search strings from the start and the end. Handle a nil result when nothing is found.
This page was last reviewed on Oct 29, 2021.
Index, rindex. Suppose we wish to search for a substring within a string. An iterator could be used, but the index() and rindex() methods are simpler.
Method notes. Index() searches from the left (or start) of the string. And rindex() searches from the end of the string—the right part first.
First example. Consider this example Ruby code. The test string contains 3 "a" characters. So the starting location of our search matters.
Detail We invoke index() to search from the start of the string. We immediately match the first letter "a," so 0 is returned.
Detail We call rindex to search from the end of the test string, and the last index 2 is returned.
test = "aaa" # Part A: use index() to search from start. left = test.index("a") puts left # Part B: use rindex() to search from end. right = test.rindex("a") puts right
0 2
No match. If no matching substring is found within the string, we get the special nil value. This can be tested in an if-statement.
Info Whenever we call index and rindex on a string, we should have code that checks for a nil result.
Detail We call index and the argument is not found in the string. The code detects this and prints a message.
Detail We invoke rindex and the argument is not found—the code prints a message to report this.
input = "test" # Part A: test index() for nil result. result1 = input.index("x") puts "NOT FOUND 1" if result1 == nil # Part B: test rindex() for nil result. result2 = input.rindex("x") puts "NOT FOUND 2" if result2 == nil
Between, before, after. In developing more complex Ruby methods, like a between method, we must use index() and rindex to search a string. And we should be careful with a nil result.
Between, before, after
A summary. Searching a string is commonly done in Ruby programs. And with index and rindex we can specify the direction, and starting position, of our search.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 29, 2021 (image).
© 2007-2023 Sam Allen.