What is the difference between << and + =?

I deal with arrays a bit and found that I do not understand the following code:

 first_array = [] second_array = [] third_array = [] # I initialized 3 empty arrays third_array << [1,2,3,4,5,6,7,8,9] # I loaded 1..9 into third_array[0] puts third_array.size # => 1 first_array << third_array # 1..9 was loaded into first_array[0] second_array += third_array # 1..9 was loaded into second_array[0] puts first_array == third_array # false puts second_array == third_array # true puts first_array == second_array # false puts first_array.size # 1 puts second_array.size # 1 puts third_array.size # 1 

What happened to this?

 second_array += third_array # I have no clue 

Why aren't all arrays equal to each other?

+6
source share
3 answers

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 
+7
source

<< add element to array

+= adds an array to the array.

Examples:

[1,2] << 3 # returns [1,2,3]

[1,2] += [3,4] # returns [1,2,3,4]

+3
source

The last difference, not mentioned so far between << and += , is that << is a method:

 class Array def << other # performs self.push( other ) end end 

whereas += is the syntax:

 a += b 

and is just a shorthand for writing:

 a = a + b 

So, to change the += behavior, you need to change the + method:

 class Array def + other # .... end end 
+3
source

Source: https://habr.com/ru/post/944477/


All Articles