Home
Ruby
String index, rindex: Find Strings
Updated Feb 2, 2024
Dot Net Perls
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 2, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen