How does negative index work with `Array#[]=`?
arrays, ruby
Solution
I would suggest you to take a look at the first para in Array documentation. It surprisingly says: “A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.”
That means, that you may set `a[-N]`th element if and only `|N| <= a.size`. That’s why `a = [1,2] ; a[-3] = 3` fails (3 > 2).
On the other hand, there is [likely] not documented feature for ruby arrays: `a[INBOUNDS_IDX..NONSENSE_IDX]=SMTH` will insert `SMTH` before `INBOUNDS_IDX` index:
a=[1,2]
a[2..0]='a'
a[2..1]='b'
a[2..-100]='c'
# ⇒ [1, 2, "c", "b", "a"]
a[2..-1]='q'
# ⇒ [1, 2, "q"]
Nonsense here means “less than INBOUNDS_IDX, and not treatable as index in an negative notation” (that’s why `a[2..-1]` in the example above is treated as `a[2..(a.size - 1)]`.)
Problem
I tried to see how `Array#[]=` works, and played around: ``` enum[int] = obj → obj enum[start, length] = obj → obj enum[range] = obj → obj ``` Question 1 I have one array `b` holding `nil` at its `0` index. ``` b = [] b[0] # => nil ``` I tried to replace `nil` with integer `10` in the code below. ``` b[-1] = 10 # => IndexError: index -1 too small for array; minimum: 0 ``` Why doesn't the code above work, but the ones below do? In case of an array with size `1`, why are the indices `0` and `-1` treated differently? ``` b[0] = 5 # => 5 b[-1] = 10 # => 10 ``` Question 2 I created an array of size `2`, and did the following: ``` a = [1,2] a[-3] = 3 # => IndexError: index -3 too small for array; minimum: -2 a[-3] = [3] # => IndexError: index -3 too small for array; minimum: -2 a[-3..-4] = [3] # => RangeError: -3..-4 out of range ``` I believe that negative index never increases the size of an array, but I don't know why. Why did the code below succeed? ``` a[-2..-3] = [3,4] #=> [3, 4] ```