2012-03-08 15 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

+0

ところで、あなたが探しているかもしれない言葉は[座標](http://dictionary.reference.com/browse/coordinate)だと思います。 – Phrogz

答えて

1

あなたはdupを使用することができます。

input_is_comment_format(array[i], comments.dup) 

ので、あなたはで動作するように配列のコピーを持っているし、あなたの元の配列は変更されません。

関連する問題