简体   繁体   English

红宝石块迭代

[英]ruby block iteration

I got confused about the iteration in ruby.In the following code I wrote, I expected that the two paths print out should be the same. 我对ruby中的迭代感到困惑。在我编写的以下代码中,我期望打印出的两个路径应该相同。 But actually they are not. 但实际上不是。 Seems the path was changed in the for loop. 似乎在for循环中更改了路径。

Anything wrong in my code? 我的代码有什么问题吗? Thanks 谢谢

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

It seems to me that problem is in this line 在我看来问题出在这一行

new_path = path

You may think that new_path and path are different objects but it's not. 您可能会认为new_pathpath是不同的对象,但事实并非如此。 I'll illustrate by example: 我将举例说明:

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

a and b are references that pointing to one object. ab是指向一个对象的引用。 The simpliest solution for you will be to use dup or clone 最简单的解决方案是使用dupclone

new_path = path.clone

but actually your code requires good cleaning. 但实际上您的代码需要良好的清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM