2015-05-22 147 views
0
def gen_path_locations(start, destination) 
    initial_dest = destination 
    last_dest = destination 
    path_locations = [] 
    loop do 
     last_dest[0] -= 1 if initial_dest[0] > start[0] 
     last_dest[0] += 1 if initial_dest[0] < start[0] 
     last_dest[1] -= 1 if initial_dest[1] > start[0] 
     last_dest[1] += 1 if initial_dest[1] < start[0] 
     break if last_dest == start 
     path_locations << last_dest 
     puts last_dest.inspect 
    end 
    path_locations 
end 

gen_path_locations([5, 5], [9, 9])回報[[5, 5], [5, 5], [5, 5]]意外的返回值

它增加了起始位置,我path_locations代替的last_dest當前迭代。當然,如果我改變了這一點:

path_locations << [last_dest[0], last_dest[1]] 

它返回期望值。我錯過了什麼?

回答

1

我錯過了什麼?

一個.clone

path_locations << last_dest.clone 

否則,您不斷添加相同的對象,其內容您不斷變化;最後,你仍然會有三次相同的對象,其內容是你改變它的最後一個。

下面是一個例子來說明:

a = ["foo", "bar"] 
b = [a, a, a] 
# => [["foo", "bar"], ["foo", "bar"], ["foo", "bar"]] 
a[1] = "quux" 
b 
# => [["foo", "quux"], ["foo", "quux"], ["foo", "quux"]] 

你可以看到發生了什麼here。該工具不適用於Ruby,但是該示例也適用於Python。

編輯:其實,here是鏈接到的代碼改寫成Python可視化 - 您可以通過一步,看看到底發生了什麼。然後用path_locations.append([last_dest[0], last_dest[1]])替換附加行,這正是你所做的(並且確切地說,Ruby的clone確實更加靈活),並且看看它如何改變程序。