They exhibit quite different behaviors. One creates and assigns a new Array object, the other modifies an existing object.
+= will be the same as second_array = second_array + third_array . This sends a + message to the second_array object, passing third_array as an argument.
The Array.+ Documentation returns a new array object constructed by combining two arrays. This will return a new object.
Array.<< just click this parameter at the end of an existing array object:
second_array = [] second_array.object_id = 1234 second_array += [1,2,3,4] second_array.object_id = 5678 second_array << 5 second_array.object_id = 5678
There is also a difference in adding a parameter. By adding other elements, this will help to understand why your arrays are not equal:
second_array = [1, 2, 3] # This will push the entire object, in this case an array second_array << [1,2] # => [1, 2, 3, [1,2]] # Specifically appends the individual elements, # not the entire array object second_array + [4, 5] # => [1, 2, 3, [1,2], 4, 5]
This is because Array.+ Uses concatenation instead of pressing. Unlike Array.concat , which modifies an existing object, Array.+ Returns a new object.
You might consider implementing a Ruby, for example:
class Array def +(other_arr) dup.concat(other_arr) end end
In your specific example, your objects look like this:
first_array = [[[1, 2, 3, 4, 5, 6, 7, 8, 9]]] # [] << [] << (1..9).to_a second_array = [[1, 2, 3, 4, 5, 6, 7, 8, 9]] # [] + ([] << (1..9).to_a) third_array = [[1, 2, 3, 4, 5, 6, 7, 8, 9]] # [] << (1..9).to_a