Ruby - Array Appending vs. Concatenating

Introduction

Concatenating using + adds the values from the second array to the first.

Appending using << adds the second array itself as the final element of the first:

Demo

a =[1,2,3] 
b =[4,5,6] #  w w w.  j av a2 s . c  om
c = a + b  #=> c=[1, 2, 3, 4, 5, 6]   a=[1, 2, 3] 
puts c
a << b     #=> a=[1, 2, 3, [4, 5, 6]] 
puts a

Result

<< modifies the first (the receiver) array, whereas + returns a new array but leaves the receiver array unchanged.

You can use the flatten method to clean up two arrays you've combined with <<, like this:

Demo

a=[1, 2, 3, [4, 5, 6]] 
puts a.flatten            #=> [1, 2, 3, 4, 5, 6]

Result

Related Topic