我在Ruby中有一个由5个空数组组成的数组。我试图使用<<
运算符将字符串推入第一个数组,但结果是字符串被推入所有数组。请帮我理解这一点。
预期输出为:
# => [["car"], [], [], [], []]
但我得到了:
# => [["car"], ["car"], ["car"], ["car"], ["car"]]
irb dump:
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\"]]"
答案 0 :(得分:6)
他们都是同一个对象:
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
答案 1 :(得分:5)
如Pedro Nascimento指出的那样,如果以这种方式初始化数组,它们都具有相同的对象id。您可以使用similar syntax创建嵌套数组来解决此问题:
irb(main):047:0> output = Array.new(5) {[]}
=> [[], [], [], [], []]
irb(main):048:0> output.each {|i| puts i.object_id}
10941700
10941680
10941660
10941640
10941620
因此,您对output[0]
的追加将按预期工作:
irb(main):049:0> output[0] << "cat"
=> ["cat"]
irb(main):050:0> output
=> [["cat"], [], [], [], []]
答案 2 :(得分:1)
代码
output = Array.new(5, [])
正在尝试只创建一个对象副本,
所以
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
如果要创建多个对象副本,请使用此
output = Array.new(5) {[]} #=> [[], [], [], [], []]
代码
output.each {|i| puts i.object_id}
会告诉你
1.9.3-p194 :005 > output.each {|i| puts i.object_id}
13417360
13417340
13417320
13417300
13417280
=> [[], [], [], [], []]