0

Let's say I would like to create a new array of arrays

arr = Array.new(5,[])
=> [[], [], [], [], []]

How can I specifically push an element to one of those arrays?

When I try to push to only one of the arrays, the value is always added to all of them:

arr[3].push("foo")
=> ["foo"]

arr
=> [["foo"], ["foo"], ["foo"], ["foo"], ["foo"]]
1
  • 1
    See the Common gotchas section in the docs for Array.new. Commented Jun 6, 2018 at 12:31

1 Answer 1

3

The problem isn't the way you're pushing, it's the way you're creating the array.

The array is initialised with 5 references to the same array, so when you modify one of them, all of the other copies change too.

You need to create the array using a different method, so that you create five different arrays rather than five copies of the same array. This can be done like so:

arr = Array.new(5) { [] }

The block (the bit between {}) is executed to create all 5 array items, so you end up with 5 different arrays.

Your code then works as expected:

arr = Array.new(5) { [] }
=> [[], [], [], [], []]

arr[3].push("foo")
=> ["foo"]

arr
=> [[], [], [], ["foo"], []]
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.