arrays - Ruby append 到数组

标签 arrays ruby append

在下面的代码行中,我期望的结果与实际结果不同。谁能帮我理解为什么?

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/

相关文章:

java - 将整数转换为字符数组 : java

C 将文本文件中的数据保存到结构体数组中

ruby-on-rails - Ruby on Rails - 选择数组中的所有 ID

ruby-on-rails - 查看上传到 AWS S3 的私有(private)图像 - 从 secret 访问 key 创建签名

c - 在 C 中评估字符串中的类型标识符 (%d)

arrays - 追加数组自定义函数不起作用

ruby-on-rails - 如何在 ruby​​ 中安装 gem 期间从 rdoc 和 ri 生成中排除某些类?

c# - 使用 C# 将数据 append 到现有的 Excel 文件

Javascript 变量相互影响