Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Q1:</strong></p> <p>An empty array has 0 elements, so when you try to set its element 0, with negative index <code>-1</code>, it will give an error. Because negative index cycles through the array from the end.</p> <p>So <code>a = []; a[-1] = 3</code> makes it impossible to </p> <p>a) get the element at last position, since its null</p> <p>b) set its value. since it was never captured.</p> <p><code>a[0] = 5</code> will work because you are telling the compiler to</p> <p>a) grab the first element, </p> <p>b) create one if not present, and then assign that to the value you requested.</p> <p>See <a href="http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-5B-5D-3D" rel="nofollow">official api doc</a> specifically mentioning positive index can grow size, negative index past the beginning of the array raises an error.</p> <p><strong>Q2:</strong></p> <p>The above explanation almost answers the second question as well.</p> <p>Given <code>a = [1,2]</code></p> <p><code>a[-3] = 3</code> causes the first point of break. You are trying to access the 3rd element from the end, which does not exist. By design it breaks down.</p> <p>While <code>a[-2..-3]</code> is within the capture range of the defined array. </p> <p>You ask the interpreter to capture the second element from the last (1st from the front in this case), and try to invoke a range which is asking it to increase the array's size, and populate it with whatever you requested.</p> <p>Happily, all is still well and as desired. Good to know.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload