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
You may think that
new_pathandpathare different objects but it’s not. I’ll illustrate by example:aandbare references that pointing to one object.The simpliest solution for you will be to use
duporclonebut actually your code requires good cleaning.