1

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?

4
  • Your second question is not clear. What do you mean by fixing it? Commented Jan 13, 2016 at 7:42
  • I assume you want %w(1 2 3 4) as the result. If I'm right, you can use a.push(*b), and in this way, a will not change with b. Commented Jan 13, 2016 at 7:48
  • 4
    Say you enter a house in a blue T-shirt, then change into a red T-shirt. If anyone takes a photo of the house, would you expect a house with someone in a blue T-shirt, or a house with someone in a red T-shirt? "But it was me that changed clothes, why did the house change?" The house didn't, but its contents did. Commented Jan 13, 2016 at 7:57
  • 1
    This visualisation is instructive (Python instead of Ruby, but otherwise exactly the same). Commented Jan 13, 2016 at 8:03

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.