我对ruby中的迭代感到困惑。在我写的下面的代码中,我预计打印出的两个路径应该是相同的。但实际上他们不是。似乎路径在for循环中已更改。
我的代码有什么问题吗?感谢
def one_step_search(dest,paths)
direction = %w(north east south west)
new_paths = []
paths.map do |path|
print "original path is: "
print_path path
curr_room = path.last
for i in 0..3
new_path = path
if !curr_room.send("exit_#{direction[i]}").nil?
next_room_tag = curr_room.send("exit_#{direction[i]}")[0]
next_room = find_room_by_tag(next_room_tag)
if !new_path.include?(next_room) # don't go back to the room visited before
new_path << next_room
new_paths << new_path
print "new path is: "
print_path path
return new_paths if dest.tag == next_room_tag
end
end
end
end
return new_paths
end
答案 0 :(得分:0)
在我看来问题就在这一行
new_path = path
您可能认为new_path
和path
是不同的对象,但事实并非如此。我将举例说明:
a = "foo"
b = a
puts a.sub!(/f/, '_')
puts a # => "_oo"
puts b # => "_oo"
a
和b
是指向一个对象的引用。
最简单的解决方案是使用dup
或clone
new_path = path.clone
但实际上您的代码需要良好的清洁。