Home
Map
String index, rindex: Find StringsUse index and rindex to search strings from the start and the end. Handle a nil result when nothing is found.
Ruby
This page was last reviewed on Feb 2, 2024.
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.
String count
First example. Consider this example Ruby code. The test string contains 3 "a" characters. So the starting location of our search matters.
Part 1 We invoke index() to search from the start of the string. We immediately match the first letter "a," so 0 is returned.
Part 2 We call rindex to search from the end of the test string, and the last index 2 is returned.
test = "aaa" # Part 1: use index() to search from start. left = test.index("a") puts left # Part 2: 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.
nil
if
Info Whenever we call index and rindex on a string, we should have code that checks for a nil result.
Part 1 We call index and the argument is not found in the string. The code detects this and prints a message.
Part 2 We invoke rindex and the argument is not found—the code prints a message to report this.
input = "test" # Part 1: test index() for nil result. result1 = input.index("x") puts "NOT FOUND 1" if result1 == nil # Part 2: test rindex() for nil result. result2 = input.rindex("x") puts "NOT FOUND 2" if result2 == nil
NOT FOUND 1 NOT FOUND 2
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.
String Between
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 Feb 2, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.