[["car"], ["car"], ["car"], [-6ren">
gpt4 book ai didi

ruby - 将字符串插入数组中的数组会产生意外结果

转载 作者:数据小太阳 更新时间:2023-10-29 07:03:35 27 4
gpt4 key购买 nike

我在 Ruby 中有一个包含 5 个空数组的数组。我正在尝试使用 <<运算符将字符串插入第一个数组,但结果是字符串被插入所有数组。请帮助我理解这一点。

预期的输出是:

# => [["car"], [], [], [], []]

但我得到:

# => [["car"], ["car"], ["car"], ["car"], ["car"]]

IRB 转储:

1.9.3-p194 :001 > output = Array.new(5, [])
=> [[], [], [], [], []]
1.9.3-p194 :002 > output.inspect
=> "[[], [], [], [], []]"
1.9.3-p194 :003 > output[0].inspect
=> "[]"
1.9.3-p194 :004 > output[0] << "car"
=> ["car"]
1.9.3-p194 :005 > output.inspect
=> "[[\"car\"], [\"car\"], [\"car\"], [\"car\"], [\"car\"]]"

最佳答案

它们都是同一个对象:

ree-1.8.7-2012.02 :001 > output = Array.new(5, [])
=> [[], [], [], [], []]
ree-1.8.7-2012.02 :002 > output[0]
=> []
ree-1.8.7-2012.02 :003 > output[0].object_id
=> 2219989240
ree-1.8.7-2012.02 :004 > output[1].object_id
=> 2219989240
ree-1.8.7-2012.02 :005 > output[2].object_id
=> 2219989240
ree-1.8.7-2012.02 :006 > output[3].object_id
=> 2219989240
ree-1.8.7-2012.02 :007 > output[4].object_id
=> 2219989240
ree-1.8.7-2012.02 :008 >

试试这个:

ree-1.8.7-2012.02 :008 > output = []
=> []
ree-1.8.7-2012.02 :009 > 5.times{output << []}
=> 5

关于ruby - 将字符串插入数组中的数组会产生意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10827202/

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