在下面的代码行中,我期望的结果与实际结果不同。谁能帮我理解为什么?
array1 = [["a", "b", "c"], ["a", "b", "c"]]
temp1 = ["x", "y", "z"]
array1 << temp1
2.times do
temp1[0] = gets.chomp #first loop enter 1 and then 4
temp1[1] = gets.chomp #first loop enter 2 and then 5
temp1[2] = gets.chomp #first loop enter 3 and then 6
puts temp1.inspect
array1 << temp1
puts array1.inspect
# Actual result: [["a", "b", "c"], ["a", "b", "c"], ["4", "5", "6"], ["4", "5", "6"], ["4", "5", "6"]]
# Expected Result: [["a", "b", "c"], ["a", "b", "c"], ["x", "y", "z"], ["1", "2", "3"], ["4", "5", "6"]]
end
最佳答案
这样做,它将起作用(将 .clone 添加到对 temp1
的所有引用):
array1 = [["a", "b", "c"], ["a", "b", "c"]]
temp1 = ["x", "y", "z"]
array1 << temp1.clone
2.times do
temp1[0] = gets.chomp #first loop enter 1 and then 4
temp1[1] = gets.chomp #first loop enter 2 and then 5
temp1[2] = gets.chomp #first loop enter 3 and then 6
puts temp1.inspect
array1 << temp1.clone
puts array1.inspect
end
# Actual result: [["a", "b", "c"], ["a", "b", "c"], ["x", "y", "z"], ["1", "2", "3"], ["4", "5", "6"]]
# Expected Result: [["a", "b", "c"], ["a", "b", "c"], ["x", "y", "z"], ["1", "2", "3"], ["4", "5", "6"]]
基本上,当您在 array1
中 append temp1
时,它是通过引用而不是通过值发生的。因此,每当更新 temp1 时,array1 中相应的 append 条目也会自动更新。为了防止这种行为,您需要在将对象 append 到数组之前clone
/dup
对象。 clone
/dup
复制对象(因此它没有相同的引用/object_id)然后分配它。
详细解释查看this发布。
关于arrays - Ruby append 到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38044813/