0

I am trying to append some values to a particular array in an array of arrays, like this:

a1 = [[]] * 2
a1[0] << -1
a1 # => [[-1], [-1]]
a2 = [[], []]
a2[0] << -1
a2 # => [[-1], []]
[[]] * 2 == [[], []] # => true

a2 has the expected value while a1 seems to be wrong. What I was expecting is a1 to have the value [[-1], []] since I changed a1[0] & not a1[1].

5
  • 2
    In the first case, the two elements are actually the same array. When you change one, the other sees the change. Commented Dec 17, 2015 at 13:00
  • How is it wrong? What is the issue? You tell us. Commented Dec 17, 2015 at 13:09
  • 1
    @sawa I have edited the answer to express what I expected. However, now I understand the issue as shivam has pointed out. Commented Dec 17, 2015 at 13:12
  • @kamalbanga in that case I was expecting my answer to be accepted :( Commented Dec 18, 2015 at 6:00
  • @shivam: When I tried to accept your answer, there was yet time to be able to do that. Later I forgot. I have accepted it now :). Commented Dec 21, 2015 at 11:29

2 Answers 2

11

You should use:

a1 = Array.new(2) { [] }

[[]]*2 is for repetition and is just repeating the same object [] twice.

To support of my above point:

a1 = [[]] * 2
a1.map(&:object_id)
#=> [26686760, 26686760]   # same object ids

a3 = Array.new(2) { [] }
a3.map(&:object_id)
#=> [23154760, 23154680]   # different object ids
Sign up to request clarification or add additional context in comments.

Comments

2

Both subarrays in your a1 are the same Array object.

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.