2016-12-01 13 views
-3

配列位置によって各数値を掛けるしようとすると、それが偽出てくるています:Ruby:なぜ私のコードは間違っていますか?

def the_sum(number) 
    i = 0 
    number = 0 
    ans = 0 

    while i < 0 
    ans = string[idx] * string.index 
    i += idx 
    end 

    return ans 
end 

test = 

the_sum([2, 3]) == 3 # (2*0) + (3*1) 

the_sum([2, 3, 5]) == 13 # (2*0) + (3*1) + (5*2) 

をし、それが偽の出てきますか?

+0

Rubyメソッドを別の方法で使用すると、[2,3,5] .map.with_index {| e、i | e * i} .inject(:+) ' –

+2

タイトルに「解決済み」を入れたり、投稿を改ざんしたりしないでください。質問を閉じるか、代わりに答えを書いてください。 – csmckelvey

答えて

1

ここでいくつかの問題

def the_sum(number) 
    i = 0 
    number = 0 # You just cleared your input variable! 
    ans = 0 

    while i < 0 # You previously i = 0 so this will never be true 
    ans = string[idx] * string.index 
    i += idx 
    end 

    return ans # Ans is and was always 0 
end 

これはあなたが渡しているArrayeach_with_indexを呼び出すことによって固定することができますがあります。

def the_array_sum(array) 
    ans = 0 

    array.each_with_index do |val, index| 
     ans += val * index 
    end 

    return ans 
end 

the_array_sum([2, 3]) == 3 
# => true 
the_array_sum([2, 3, 5]) == 13 
# => true 
関連する問題