由于某种原因而改变的价值问题
Problem with Value That change for some reason
只需 运行 控制台中的这段代码。
问题是 @notes_before 由于某些原因在调用方法 "a.move" 后更改值。
如何解决它以及为什么会发生?
class Slider
attr_accessor :position
def initialize(position)
@position = position
@notes_before = Array.new
end
def move
@position.each do |note|
note[0] +=1
end
print @notes_before
end
def update_pos
@position.each do |notes|
@notes_before << notes
end
print @notes_before
end
end
a=Slider.new([[0,0],[0,1]])
a.update_pos
a.move
我希望调用 a.move 后 @notes_before 的输出为 [[0, 0], [0, 1]] 但实际输出为 [[1, 0], [ 1, 1]]
您正在通过引用而非值复制数组。因此,当第一个数组更改时,第二个数组也会更改,因为它们共享相同的引用。
您可以采取以下措施来避免此问题:
class Slider
attr_accessor :position
def initialize(position)
@position = position
@notes_before = Array.new
end
def move
@position.each do |note|
note[0] +=1
end
print @notes_before
end
def update_pos
@notes_before = @position.map(&:clone)
print @notes_before
end
end
a=Slider.new([[0,0],[0,1]])
a.update_pos
a.move
只需 运行 控制台中的这段代码。 问题是 @notes_before 由于某些原因在调用方法 "a.move" 后更改值。 如何解决它以及为什么会发生?
class Slider
attr_accessor :position
def initialize(position)
@position = position
@notes_before = Array.new
end
def move
@position.each do |note|
note[0] +=1
end
print @notes_before
end
def update_pos
@position.each do |notes|
@notes_before << notes
end
print @notes_before
end
end
a=Slider.new([[0,0],[0,1]])
a.update_pos
a.move
我希望调用 a.move 后 @notes_before 的输出为 [[0, 0], [0, 1]] 但实际输出为 [[1, 0], [ 1, 1]]
您正在通过引用而非值复制数组。因此,当第一个数组更改时,第二个数组也会更改,因为它们共享相同的引用。
您可以采取以下措施来避免此问题:
class Slider
attr_accessor :position
def initialize(position)
@position = position
@notes_before = Array.new
end
def move
@position.each do |note|
note[0] +=1
end
print @notes_before
end
def update_pos
@notes_before = @position.map(&:clone)
print @notes_before
end
end
a=Slider.new([[0,0],[0,1]])
a.update_pos
a.move