Messi
Messi

Reputation: 97

Array element is modified

Here is my challenge.

a = ["1", "2"]
b = ["3", "4"]
a << b
a # => ["1","2",["3","4"]] 

If I modify the value of b[0], a also is changed.

b[0] = "5"
a # => ["1","2",["5","4"]]

After pushing b into a, b was modified. Why is a changed, and how can I fix it?

Upvotes: 1

Views: 60

Answers (1)

Wand Maker
Wand Maker

Reputation: 18762

The array instance that is referenced by b and the one that is pushed into a, both are same instance - hence, modifying one will result in changes seen in other as well.

You can try:

a << b.dup

so that a copy of b is pushed into a.

Upvotes: 4

Related Questions