2011-12-22 76 views
2

這是我的功能有人可以澄清爲什麼我的循環中變量的值不更新,直到循環關閉?

def rating(array) 
    sum_count = array.values.inject(0) { |sum_count,value| sum_count + value } 
    run_count = 0 
    array.each do |tag,count| 
    run_count += count 
    cum_distn = run_count/sum_count 
    logger.debug "cum_distn is #{cum_distn.to_f}; run_count is #{run_count.to_f}; sum_count is #{sum_count}" 
    if cum_distn < 0.25 
     ... 
    elsif cum_distn < 0.5 
     ... 
    else 
     ... 
    end 
    end 
end 

對於我的陣列的每1計數2個目的,我的記錄器示出該:

cum_distn is 0.0; run_count is 1.0; sum_count is 2 
cum_distn is 1.0; run_count is 2.0; sum_count is 2 

似乎cum_distn的值只更新一次一個循環完成,而我打算在if函數打開之前立即更新。我有兩個問題:

(a)爲什麼會發生這種情況(因爲我看不到任何合理的解釋)? (b)我如何糾正這一點,做我想做的事?

+0

尚未讀完你的問題,但你應該取代因爲'hash.values'比'array.values'更有意義...' – Damien 2011-12-22 15:56:37

回答

3

您正在使用整數除法,因此run_count/sum_count的結果會被截斷。要修復,只需在計算cum_distn之前將其中一個轉換爲Float即可。例如:

cum_distn = run_count.to_f/sum_count 
+0

我的菜鳥錯誤。因爲'def rating(hash)''def def rating(array)'。非常感謝 – 2011-12-22 16:35:16

2

1)這是因爲3/2 #=> 13.0/2 # => 1.5。在其他方面,integer/integer #=> integerfloat/integer #=> float

2)只需撥打to_f一次,一開始(而不是在一個循環,因爲它真的不是高性能的):

def rating(hash) 
    sum_count = hash.values.inject(:+).to_f 
    hash.inject(0) do |run_count, (tag, count)| 
    run_count += count 
    cum_dist = run_count/sum_count 
    logger.debug "cum_distn is #{cum_distn}; run_count is #{run_count}; sum_count is #{sum_count}" 
    ... 
    run_count # return run_count 
    end 
end 
+0

感謝您的詳細解釋 – 2011-12-22 16:35:05