2.14. Searching a String

Besides the techniques for accessing substrings, there are other ways of searching within strings. The index method returns the starting location of the specified substring, character, or regex. If the item is not found, the result is nil:

str = "Albert Einstein"
pos1 = str.index(?E)        # 7
pos2 = str.index("bert")    # 2
pos3 = str.index(/in/)      # 8
pos4 = str.index(?W)        # nil
pos5 = str.index("bart")    # nil
pos6 = str.index(/wein/)    # nil

The method rindex (right index) starts from the righthand side of the string (that is, from the end). The numbering, however, proceeds from the beginning as usual:

str = "Albert Einstein" pos1 = str.rindex(?E) # 7 pos2 = str.rindex("bert") # 2 pos3 = str.rindex(/in/) # 13 (finds rightmost match) ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.