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?

sawa
  • 165,429
  • 45
  • 277
  • 381
Ghanshyam Anand
  • 164
  • 1
  • 10

2 Answers2

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.

Lix
  • 47,311
  • 12
  • 103
  • 131
  • So is `<<` like `array.append`? – Arc676 Mar 10 '16 at 13:01
  • @Arc676 - Yes. This is my intention. – Lix Mar 10 '16 at 13:02
  • 1
    This post http://stackoverflow.com/questions/1801516/how-do-you-add-an-array-to-another-array-in-ruby-and-not-end-up-with-a-multi-dim, while not directly related to your question contains useful and relevant information to your issue. – Lix Mar 10 '16 at 13:02
  • What do you mean by "there is no **need** to create a new object"? `<<` just **doesn't** create a new object. – sawa Mar 10 '16 at 13:42
  • @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. – Lix Mar 10 '16 at 13:45
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.

AnoE
  • 8,048
  • 1
  • 21
  • 36