in Ruby 2.6.6, I wanted to pre-create an array of arrays, and insert some values into one index. What I notice is the array puts all values into all arrays when doing like this:
matrix = Array.new( 3, [] )
5.times do |n| matrix[0] << n end
p matrix
# outputs: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
What I was hoping to get to:
[[0, 1, 2, 3, 4], [], []]
How should I do this the right way?
CodePudding user response:
It's a problem with your array instantiation.
It should be
matrix = Array.new(3){Array.new}
From the 2.6.6 documentation:
Array.new(3, true) #=> [true, true, true]
Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.
To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:
Array.new(4) {Hash.new} #=> [{}, {}, {}, {}]