Q1:
An empty array has 0 elements, so when you try to set its element to 0 with a negative index of -1 it will throw an error. Since a negative index cycles through the array from the end.
So, a = []; a[-1] = 3 a = []; a[-1] = 3 makes it impossible
a) get the element in the last position, since its null
b) set its value. since he was never captured.
a[0] = 5 will work because you tell the compiler
a) take the first element,
b) create one, if not, and then assign that value that you requested.
See the official api doc for a positive index, size may increase, a negative index preceding the beginning of the array causes an error.
Q2:
The above explanation almost also answers the second question.
Given a = [1,2]
a[-3] = 3 causes the first break point. You are trying to access the third element from an end that does not exist. By design, it breaks.
While a[-2..-3] is in the capture range of a specific array.
You ask the interpreter to grab the second element from the last (the first in this case in this case) and try to call a range that asks it to increase the size of the array and fill it with what you requested.
Fortunately, everything is still good and at will. Good to know.
source share