gpt4 book ai didi

Ruby:对数组元素的赋值

转载 作者:数据小太阳 更新时间:2023-10-29 08:59:41 24 4
gpt4 key购买 nike

我是初学者,我想创建一个矩阵。例如:

0 1 1
1 1 1
1 1 2

irb(main):001:0> t = [[1]*3]*3
=> [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
irb(main):002:0> (0...3).each do |x| t[x][x]=x end
=> 0...3
irb(main):003:0> t
=> [[0, 1, 2], [0, 1, 2], [0, 1, 2]] # why all values changed?

怎么了?

最佳答案

构造数组的方式不会为每一行创建新数组,而是为所有行引用相同的数组:

t.each do |row|
p row.object_id
end

# 70325094342320
# 70325094342320
# 70325094342320

它等同于:

a = [1, 1, 1]
t = [a, a, a]

试试看区别:

t = [[1] * 3, [1] * 3, [1] * 3]

关于Ruby:对数组元素的赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39471424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com