我有这样的东西:
good_attrs = %w(firm_size priority_level)
good_attrs.each do |attr|
if (score.send(attr) > max.send(attr))
max.send("#{attr}=", score.send(attr))
end
end
不过,有时它可能会遇到如下所示的 Max
记录:
#<Max:0x007fe01024b240> {
:id => 2,
:user_id => 1,
:firm_size => 101.0,
:priority_level => nil,
:created_at => Fri, 23 Nov 2012 01:55:53 UTC +00:00,
:updated_at => Fri, 23 Nov 2012 01:58:16 UTC +00:00
}
即max.priority_level
= nil
。
那么我该如何修改我的初始 if 语句
以处理评估双方的 nil
情况?即,如果 score
或 max
属性为 nil。理想情况下,我希望它被视为 0
并相应地进行。
最佳答案
您不能将 nil
与 Float
进行比较。
在您的情况下,您可以利用 nil.to_f == 0.0
这一事实:
good_attrs = %w(firm_size priority_level)
good_attrs.each do |attr|
if score.send(attr).to_f > max.send(attr).to_f
max.send("#{attr}=", score.send(attr))
end
end
关于ruby-on-rails - 如何比较 Float 和 Nil 以返回有效答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13573979/