I've come across a code snippet where index access is defined with a range ending with a minus value.
array[1..-2]
What's the purpose of this?
Best Answer
In Ruby (as well as Python, Perl, and a few other languages), a negative array index is interpreted relative to the end of the array. array[-1]
is the last element of the array; array[-2]
is the next to last.
So this is a slice of the array omitting the first and last elements.
Arrays are Zero Indexed meaning they start at 0 instead of 1. For example, let's suppose we created an array
numbers = [1,2,3,4,5,6,7,8,9,10]
The first array element, which is indexed at 0 and is indicated by numbers[0] would return 1. Here are the indices
[0,1,2,3,4,5,6,7,8,9]
Meaning this numbers array is indexed from 0 to 9 and not 1 to 10.
There are two methods for finding the last value of an array.
numbers[8]
or if you didn't know the number of values in an array you could do
numbers[-1]
This would return the number 9.
What you mentioned is the range notation, indicated by a starting value, two consecutive dots and an ending value.
In your example
array[1..-2]
Means it would return all values of the array starting with the 2nd element and ending with the 2nd to last element. If we called it on my numbers array
numbers[1..-2]
It would return
[2,3,4,5,6,7,8,9]
In other words all values inclusive starting at the second value(2) and ending at the second to last value (9). On the other hand
numbers[1...-2]
with 3 dots indicate the range is exclusive and contains all values starting at the second value BENEATH the second to last value.
Hope this helps.
That is taking all the elements from the second element to the second-to-last element. In other words, it truncates the first and last element. See this link for more information on negative array indices.