我在
Ruby中有一个由5个空数组组成的数组.我正在尝试使用<<运算符将字符串推入第一个数组,但结果是字符串被推入所有数组.请帮我理解这个. 预期的产出是:
# => [["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\"]]"
解决方法
他们都是同一个对象:
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