2012-03-08 83 views
0

我試圖通過循環執行嵌套數組的操作。該循環執行一次,但然後我得到一個nomethod錯誤,因爲該變量未被重置。Ruby - 通過循環迭代時保護變量

array = [[9, 2, 0, 0], [4, 1, 2, 2], [7, 1, 5, 5], [6, 1, 3, 1]] 
comments = [[0, 0, 0], [1, 1, 1], [2, 2, 2]] 

def shift_comments(array) 
    array.each {|x| x.shift} 
end 

def map_distance_coordinants(array) 
    array2 = array.map {|x,y| [Math.sqrt(x*x + y*y)]} 
    array2 
end 

def input_is_comment_format(array, comments) 

    distance_coordinants = shift_comments(comments) 

    mapped_coordinanats = map_distance_coordinants(distance_coordinants) 

    print mapped_coordinanats 
    print comments 
end 

i = 0 
while i < array.length 
    input_is_comment_format(array[i], comments) 
    i += 1 
end 

返回:

[[0.0], [1.4142135623730951], [2.8284271247461903]][[0, 0], [1, 1], [2, 2]] 
temp4.rb:9:in `block in map_distance_coordinants': undefined method `*' for nil:NilClass (NoMethodError) 

如何保護的意見「,這樣我可以使用它的每次循環?謝謝。

+1

我無法從所有這些代碼中掌握您的願望。如果你沒有得到很好的答案,你可以考慮把它歸結爲更一般的情況,並指定你想要的輸出。 – Phrogz 2012-03-08 18:03:54

+0

順便說一句,我想你可能正在尋找的詞是[座標](http://dictionary.reference.com/browse/coordinate)。 – Phrogz 2012-03-08 18:09:00

回答

1

你可以使用dup

input_is_comment_format(array[i], comments.dup) 

讓你有數組的一個副本,你的原始數組不會被修改工作。