6

我在 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\"]]" 
4

3 回答 3

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 
于 2012-05-31T03:54:56.370 回答
5

正如 Pedro Nascimento 所指出的,如果数组以这种方式初始化,它们都具有相同的对象 ID。您可以通过使用类似的语法来创建嵌套数组来解决此问题:

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"], [], [], [], []]
于 2012-05-31T04:04:31.380 回答
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
 => [[], [], [], [], []] 
于 2012-05-31T04:30:53.903 回答