我对那段代码有问题。
temp_state = @state
Run Code Online (Sandbox Code Playgroud)
我想要做的是将我的实例变量@state 的值分配给一个新的局部变量 temp_state。问题是当我做
temp_state.object_id = 70063255838500
state.object_id = 70063255838500
Run Code Online (Sandbox Code Playgroud)
当我修改 temp_state 时,我也在修改 @state。如何在不修改@state 的内容的情况下使用 temp_state?
以下是课程的重要部分:
class SearchNode
attr_accessor :state, :g, :f, :free_index
def initialize(state, parent = self)
@state = state
@g = parent == self ? 1 : parent.g
@h = calculate_h
@f = @g + @h
@valid_action = ["Move(Black)", "Move(Red)", "Jump(Black)", "Jump(Red)"]
@free_index = index_of_free
@parent = parent
end
def move_black_jump
free = @free_index
# PROBLEM NEXT LINE
temp_state = @state
if temp_state[free + 2] == 'B' || temp_state[free - 2] == 'B'
if free - 2 >= 0 && free + 2 <= temp_state.length
index = free - 2 if temp_state[free - 2] == 'B'
index = free + 2 if temp_state[free + 2] == 'B'
else
puts "ERROR: Movement out of bounds."
end
x = temp_state[index]
temp_state[index] = 'F'
temp_state[free] = x
else
puts "ERROR: Wrong movement move_black_jump."
end
return temp_state
end
end
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助。
您必须制作对象的副本,而不是传递给同一对象的新变量引用。您使用Object#dup方法进行(浅)复制:
temp_state = @state.dup
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
845 次 |
| 最近记录: |