user810606
user810606

Reputation:

What is the difference between #concat and += on Arrays?

I want to concatenate two Arrays in Ruby. So far I have found the #concat and the += operator. They seem to produce the same result, but I want to know what is the difference between them.

Upvotes: 4

Views: 1750

Answers (1)

bjhaid
bjhaid

Reputation: 9752

+= would create a new array object, concat mutates the original object

a = [1,2]
a.object_id # => 19388760 
a += [1]
a.object_id # => 18971360 


b = [1,2]
b.object_id # => 18937180 
b.concat [1]
b.object_id # => 18937180 

Note the object_id for a changed while for b did not change

Upvotes: 12

Related Questions