October 2006
Intermediate to advanced
888 pages
16h 55m
English
In Ruby, substrings may be accessed in several different ways. Normally the bracket notation is used, as for an array, but the brackets may contain a pair of Fixnums, a range, a regex, or a string. Each case is discussed in turn.
If a pair of Fixnum values is specified, they are treated as an offset and a length, and the corresponding substring is returned:
str = "Humpty Dumpty" sub1 = str[7,4] # "Dump" sub2 = str[7,99] # "Dumpty" (overrunning is OK) sub3 = str[10,-4] # nil (length is negative)
It is important to remember that these are an offset and a length (number of characters), not beginning and ending offsets.
A negative index counts backward from the end of the string. In this case, the index is ...
Read now
Unlock full access