Reputation: 9889
See the sample code first:
arr = [4, 5, 6]
arr[2] = ["a","b","c"] # First Update
print arr.join(","), ", len=", arr.length, "\n"
print arr[2] ,"\n"
arr[0..1] = [7,"h","b"] # Second Update
print arr.join(","), ", len=", arr.length, "\n"
Output is:
4,5,a,b,c, len=3
abc
7,h,b,a,b,c, len=4
With the first update, only element 2 is updated to "abc". But with the second update, updating 3 elements to 2 existing elements leads to insert one element, so array length increase 1.
My question is that why the first update doesn't lead to element insertion? What's the rule?
Upvotes: 0
Views: 563
Reputation: 122383
The first update raplaces one element in the array with an array to arr
, use p arr
to check out:
[4, 5, ["a", "b", "c"]]
The second update raplaces two elements in the array with an array:
[7, "h", "b", ["a", "b", "c"]]
The rule is :
Upvotes: 1
Reputation: 29389
The difference is because you used a range in the second case and not the first. When you use a range as an index on the left hand side of the assignment, Ruby replaces those elements with the individual elements from the array on the right hand side. When an integer is used as an index on the left hand side, that element is replaced with the entire array from the right hand side.
If you'd instead said arr[2..2] = ['a', 'b', 'c']
in your first update, the array length would have gone from 3 to 5 (i.e. the array would have become [4, 5, 'a', 'b', 'c']).
The official documentation on this is at http://ruby-doc.org/core-2.0/Array.html#method-i-5B-5D-3D
Upvotes: 2
Reputation: 2257
After the first update, you replace the third element with another array. So your array looks like the following:
[4, 5, ["a", "b", "c"]]
That's why the length of resulting array is 3.
Upvotes: 0