October 2006
Intermediate to advanced
888 pages
16h 55m
English
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/) # nilThe 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) ...Read now
Unlock full access