String[1..-1] how does this refer to the last character in the array?



I understand that [1] refers to the second character in the array, since [0] is the first one. I also understand that the two dots mean that the end of the range is included.
But how [-1] is the last character? Does that mean that [..] somehow counts the number of characters in the array (from 1 to the last character) so I have to subtract 1 from the number of the last character to get it's position in the array?



In Ruby, negative indexes always work relative to the end of the array (as opposed to an absolute index like [0] .. [n]), regardless of the number of items in the array.

So as you say, [-1] would be the last element, [-2] the second-last, and so on. Naturally this means an IndexError will be thrown if you use a negative index that points past the start of the array.


I see, thanks a lot! :slightly_smiling: