As a rule, indexes help me:
# 0 1 2 3 4 5 6 7 8 9 10 11 12 str = 'a' 'n' 'y' 't' 'h' 'i' 'n' 'g' ' ' 'e' 'l' 's' 'e'
You can refer to each character by its positive or negative index. For example, you can use 3 or -10 to mean "t" :
str[3] #=> "t" str[-10] #=> "t"
and 7 or -6 to refer to "g" :
str[7] #=> "g" str[-6] #=> "g"
Similarly, you can use each of these indices to retrieve the "thing" across a range:
str[3..7] #=> "thing" str[3..-6] #=> "thing" str[-10..7] #=> "thing" str[-10..-6] #=> "thing"
str[-1..1] , however, will return an empty string, because -1 refers to the last character, and 1 refers to the second. This would be equivalent to str[12..1] .
But if the string consists of one character, this range becomes valid:
# 0 str = '1'
In fact, 1 refers to the index after the first character, so 0 will be enough:
str[-1..0] #=> "1"
source share