0

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?

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 :

  1. If used with a single integer index, the element at that position is replaced by whatever is on the right side of the assignment.
  2. If used with a range, then those elements in the original array are replaced by whatever is on the right side of the assignment. And the right side is itself an array, its elements are used in the replacement.

Comments

0

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.

1 Comment

I know this. But why after the second update, one element get inserted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.