TieDad
TieDad

Reputation: 9889

Ruby array update operation

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

Answers (3)

Yu Hao
Yu Hao

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 :

  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.

Upvotes: 1

Peter Alfvin
Peter Alfvin

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

Konstantin Rudy
Konstantin Rudy

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

Related Questions