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. But actually they are not. Seems the path was changed in the for loop.
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. 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. The simpliest solution for you will be to use dup
or clone
new_path = path.clone
but actually your code requires good cleaning.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.