kamalbanga
kamalbanga

Reputation: 2011

Ruby gives different results for different approaches to array of arrays

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].

Upvotes: 0

Views: 73

Answers (2)

shivam
shivam

Reputation: 16506

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

Upvotes: 11

Marek Lipka
Marek Lipka

Reputation: 51181

Both subarrays in your a1 are the same Array object.

Upvotes: 2

Related Questions