【问题标题】:Pushing an array into another array overwrites all the elements in the second array将一个数组推入另一个数组会覆盖第二个数组中的所有元素
【发布时间】:2021-03-20 03:25:09
【问题描述】:

我正在编写一个方法来修改临时变量中的数组,然后将该变量推送到多维数组中。但是当我将 temp 变量推入多维数组时,所有内容都会被 temp 的值覆盖。方法是这样的:

def possible_moves(start, moves = [])
  return if start.any?(nil)

  temp = []

  # add 2 to first, add 1 to last

  temp << start.first + 2  
  temp << start.last + 1

  moves << temp

  # add 2 to first, subtract 1 to last

  temp.pop 
  temp << start.last - 1

  moves << temp

  moves
end

如果我使用start = [3, 4] 运行该方法,那么结果是

moves = [[5, 3], [5, 3]]

预期结果应该是什么时候

moves = [[5, 5], [5, 3]]

另外,使用Array#push 代替Array#&lt;&lt; 会得到相同的结果。

我对编程很陌生,很难弄清楚发生了什么以及如何解决它,因此非常感谢任何帮助。我正在使用 Ruby 2.7.0。

【问题讨论】:

    标签: arrays ruby


    【解决方案1】:
    def possible_moves(start, moves = [])
      return if start.any?(nil)
    
      temp = []
    
      # add 2 to first, add 1 to last
    
      temp << start.first + 2  
      temp << start.last + 1
    
      moves << [*temp]
      #or moves << temp.dup
    
      # add 2 to first, subtract 1 to last
    
      temp.pop 
      temp << start.last - 1
    
      moves << [*temp]
      #or moves << temp.dup
    
      moves
    end
    

    上述行为的原因是当您将一个数组推入另一个数组时,不会复制推入的数组,而是复制它的引用,因此当您更改源数组时。它在其他数组中的值发生变化。这是一个简单的插图来说明这一点

    ar1 = [1,2,3]
    ar2 = [ar1,[5,6]] # [[1, 2, 3], [5, 6]]
    ar1[0] = 99 
    

    现在检查 ar2 ,它将是 [[99, 2, 3], [5, 6]]

    您可以通过检查任何 ruby​​ 对象的object_id 来验证它

    ar1.object_id => 某个数字

    ar2[0].object_id => 又是同一个号码

    【讨论】:

    • 谢谢。这解决了问题。
    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 2012-03-31
    • 1970-01-01
    • 2013-03-03
    • 2022-11-12
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    相关资源
    最近更新 更多