Index
, rindexSuppose we wish to search for a substring within a string
. An iterator could be used, but the index()
and rindex()
methods are simpler.
Index()
searches from the left (or start) of the string
. And rindex()
searches from the end of the string
—the right part first.
Consider this example Ruby code. The test string
contains 3 "a" characters. So the starting location of our search matters.
index()
to search from the start of the string
. We immediately match the first letter "a," so 0 is returned.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 right0 2
If no matching substring is found within the string
, we get the special nil
value. This can be tested in an if
-statement.
string
, we should have code that checks for a nil
result.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 == nilNOT FOUND 1 NOT FOUND 2
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.
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.