2

Suppose I declare arrays as follows:

array1 = [1,2,3,4,5] array2 = array1 

The object ID of both arrays are the same:

array1.object_id = 118945940 array2.object_id = 118945940 

When I insert an element in an array as follows,

array1 << 10 

the result is

array1 = [1, 2, 3, 4, 5, 10] array2 = [1, 2, 3, 4, 5, 10] 

But when I add new array into array array1,

array1 = array1 + [11,12] array1 = [1,2,3,4,5,10,11,12] array2 = [1,2,3,4,5,10] 

the object ID of both arrays have changed.

How does << work?

2 Answers 2

3

I believe that the confusion here is due to the fact that concatenating two arrays actually creates a new array (ie: a new object).

array1 + array2 

This will create a new array with the contents of both arrays inside. So the object id will change because it is a different object.

When you use the << operator it just adds an element to the array - ruby doesn't create a new object and hence both arrays (which share an object id) get the new element.

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

5 Comments

So is << like array.append?
@Arc676 - Yes. This is my intention.
This post stackoverflow.com/questions/1801516/…, while not directly related to your question contains useful and relevant information to your issue.
What do you mean by "there is no need to create a new object"? << just doesn't create a new object.
@sawa - perhaps the wrong choice of words... What I mean is that appending an element to an array does not create a new object. You don't need to use code/methods that creates a new object.
1

array is a variable containing a reference (pointer, handle, ID - whatever you want to call it) to the actual array (the instance of class Array).

array (variable) -------------------> object (instance of class Array) 

What does your code do? Let's see:

array << value 

This is exactly the same as calling a method: array.append(value). No new instance of Array is created. You are not assigning a new value to the variable array. The actual array object is of course changing, but not its reference.

array1 = array1 + array2 

The right side of the assignment, array1 + array2, must necessarily create a new Array instance. This is easy to see - the code intuitively should not modify array1 or array2. The reference to this new array is then stored in the variable array1.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.