【发布时间】:2016-12-19 09:52:29
【问题描述】:
temp 得到@board.dup,@board 数组被修改。但是,temp 也会被修改!我已尝试阅读所有相关文档,但仍然无法找到解释。
class Test
def initialize
@board = [[1,2],[3,4], [5,6]]
end
def modify
temp = @board.dup #Also tried .clone
print 'temp: ';p temp
print '@board: ';p @board
@board.each do |x|
x << "x"
end
print "\ntemp: ";p temp
print '@board: ';p @board
end
end
x = Test.new
x.modify
输出:
temp: [[1, 2], [3, 4], [5, 6]]
@board: [[1, 2], [3, 4], [5, 6]]
temp: [[1, 2, "x"], [3, 4, "x"], [5, 6, "x"]] # <= Why did it change?
@board: [[1, 2, "x"], [3, 4, "x"], [5, 6, "x"]]
我能做些什么来确保 temp 不被修改?
【问题讨论】:
-
这是同一个引用,例如,
temp指向同一个数组@board是。如果您想保留原始版本,则必须克隆它。 -
抱歉,编辑了我的问题。我确实在我的代码中做了
@board.dup。但是温度也变了。 (也尝试了.clone,仍然是相同的输出) -
你必须克隆很深。
标签: ruby variables scope instance-variables