Ruby 中的多维数组正在用重复项填充所有索引
a multidimensional arrays in Ruby is filling all indexes with duplicates
在Ruby 2.6.6 中,我想预先创建一个数组数组,并将一些值插入到一个索引中。我注意到数组在这样做时将所有值放入所有数组:
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]]
我希望达到的目标:
[[0, 1, 2, 3, 4], [], []]
我应该如何正确执行此操作?
你的数组实例化有问题。
应该是
matrix = Array.new(3){Array.new}
来自 2.6.6 文档:
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} #=> [{}, {}, {}, {}]
在Ruby 2.6.6 中,我想预先创建一个数组数组,并将一些值插入到一个索引中。我注意到数组在这样做时将所有值放入所有数组:
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]]
我希望达到的目标:
[[0, 1, 2, 3, 4], [], []]
我应该如何正确执行此操作?
你的数组实例化有问题。
应该是
matrix = Array.new(3){Array.new}
来自 2.6.6 文档:
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} #=> [{}, {}, {}, {}]