这是我的功能
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 :(得分:3)
您正在使用整数除法,因此run_count / sum_count
的结果会被截断。要进行修复,只需将其中一个转换为Float
,然后再计算cum_distn
。例如:
cum_distn = run_count.to_f / sum_count
答案 1 :(得分:2)
1)这是因为3/2 #=> 1
但3.0/2 # => 1.5
。换句话说,integer/integer #=> integer
和float/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