我对那段代码有疑问。
temp_state = @state
我想要做的是将我的实例变量@state 的值分配给一个新的局部变量 temp_state。问题是当我这样做时
temp_state.object_id = 70063255838500
state.object_id = 70063255838500
当我修改 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
谢谢您的帮助。