2016-12-01 49 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