Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 将一个数组推入另一个数组会覆盖第二个数组中的所有元素_Arrays_Ruby - Fatal编程技术网

Arrays 将一个数组推入另一个数组会覆盖第二个数组中的所有元素

Arrays 将一个数组推入另一个数组会覆盖第二个数组中的所有元素,arrays,ruby,Arrays,Ruby,我正在编写一个方法,修改临时变量中的数组,然后将该变量推入多维数组。但是当我将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

我正在编写一个方法,修改临时变量中的数组,然后将该变量推入多维数组。但是当我将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
预期的结果应该是什么时候

moves = [[5, 5], [5, 3]]
另外,使用
Array#push
而不是
Array#
现在检查ar2,它将是
[[99,2,3],[5,6]]

您可以通过检查任何ruby对象的
object\u id
来验证它

ar1.object\u id
=>somenumber


ar2[0]。对象id
=>samenumber再次

谢谢。这解决了问题。
moves = [[5, 5], [5, 3]]
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