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