0

我对 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
4

1 回答 1

0

在我看来问题出在这一行

new_path = path

你可能认为new_pathandpath是不同的对象,但事实并非如此。我将举例说明:

a = "foo"
b = a
puts a.sub!(/f/, '_')
puts a                   # => "_oo"
puts b                   # => "_oo"

a并且b是指向一个对象的引用。对您来说最简单的解决方案是使用dupclone

new_path = path.clone

但实际上你的代码需要很好的清理。

于 2012-11-05T04:05:40.493 回答