Ruby-更改实例变量时修改本地变量 [英] Ruby - local variable gets modified when changing instance variable
本文介绍了Ruby-更改实例变量时修改本地变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
temp
获取 @ board.dup
,并修改 @board
数组.但是, temp
也会被修改!我已经尝试阅读所有相关文档,但仍然找不到解释.
temp
gets @board.dup
, and @board
array is modified. However, temp
gets modified as well! I have tried reading all the related documentations but still couldn't figure out an explanation.
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"]]
我该怎么做才能确保温度不被修改?
What can I do to ensure temp doesn't get modified?
推荐答案
您拥有带有数组的数组,因此您将第一个数组复制了,但是内部对象指向了同一实例.在这种情况下,您只需修改相同的源即可.
You have Array with Arrays, so you dup the first array but, inside object point to the same instance. In this case you just modify the same source.
喜欢这里:
arr = [[1, 2, 3]]
arr2 = arr.dup
arr2[0] << 1
p arr
# => [[1, 2, 3, 1]]
p arr2
# => [[1, 2, 3, 1]]
因此,对于所有这样的数组实例,必须使用 dup
.
So you must use dup
for all array instance like this.
arr = [[1, 2, 3]]
arr3 = arr.map(&:dup)
arr3[0] << 1
p arr
# => [[1, 2, 3]]
p arr3
# => [[1, 2, 3, 1]]
在您的情况下,请使用此 map
.
In your case use this map
.
class Test
def initialize
@board = [[1,2],[3,4], [5,6]]
end
def modify
temp = @board.map(&:dup) # dup all
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], [3, 4], [5, 6]]
# @board: [[1, 2, "x"], [3, 4, "x"], [5, 6, "x"]]
这篇关于Ruby-更改实例变量时修改本地变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文