这是我的功能
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) 我该如何纠正这个问题以实现我想要的目的?
最佳答案
您正在使用整数除法,因此 run_count/sum_count
的结果会被截断。要解决此问题,只需在计算 cum_distn
之前将其中之一转换为 Float
即可。例如:
cum_distn = run_count.to_f / sum_count
关于ruby - 有人可以澄清为什么循环中变量的值在循环关闭之前不会更新吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8606267/