【发布时间】: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#<< 会得到相同的结果。
我对编程很陌生,很难弄清楚发生了什么以及如何解决它,因此非常感谢任何帮助。我正在使用 Ruby 2.7.0。
【问题讨论】: