2012-03-08 81 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) 

让你有数组的一个副本,你的原始数组不会被修改工作。