我是ruby的首发,我真的坚持使用这段代码......我无法理解为什么@plays会在调用test_code时发生变化
class Board
attr_reader :plays
def initialize(secret_code)
@secret_code = secret_code
@plays = []
end
def insert_code(code)
@plays.push(code)
p @plays #-> [["red", "red", "red", "red"]]
test_code(code) #-> When i call this method the changes on 'code' make to '@plays' array...
p @plays #-> [["check", "red", "red", "red"]]
end
private
def test_code(code)
s_code = @secret_code # made a copy of @secret_code to keep it intact but is changing just like @plays
s_code.each_index do |i|
if s_code[i] == code[i]
s_code[i] = "O"
code[i] = "check" #in this line the @plays array is changed, and i can't figure out why
end
end
end
end
board = Board.new(["red", "blue", "blue", "blue"])
board.insert_code(["red", "red", "red", "red"])
答案 0 :(得分:1)
赋值运算符=
不会复制对象。它为对象创建一个新的引用(即指针)。
您可以使用clone
创建对象的浅表副本,如下所示:
...
s_code = @secret_code.clone
...
def test_code(code0)
code = code0.clone
...
答案 1 :(得分:0)
你像这样定义了@plays:
def insert_code(code)
@plays.push(code) # here is not a clone but a quote
end
运行methond&#34; test_code&#34;后,变量&#34; code&#34>更改为[&#34;检查&#34;,&#34;红色&#34;,&#34;红色&#34;,&#34;红色&#34;] 所以你看@plays也改为[[&#34; check&#34;,&#34; red&#34;,&#34; red&#34;,&#34; red&#34;]] < / p>