Reputation:
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.
+=
operator?#concat
and using the +=
operator on Arrays?Upvotes: 4
Views: 1750
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