[英]How do I get a comparison of Float & Nil to return a valid answer?
I have something like this: 我有这样的事情:
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
What happens, though, is that occassionally it may come across a Max
record that looks like this: 然而,会发生的事情是偶尔可能会遇到如下所示的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
}
ie max.priority_level
= nil
. 即max.priority_level
= nil
。
So how do I modify my initial if statement
to handle nil
cases on both sides of the evaluation? 那么如何修改我的初始if statement
来处理评估双方的nil
个案? ie if a score
or max
attribute is nil. 即,如果score
或max
属性为零。 Ideally, I would like it to be treated as 0
and proceed accordingly. 理想情况下,我希望将其视为0
并相应地进行处理。
You can't compare nil
with a Float
. 你无法将nil
与Float
进行比较。
In your case you can take advantage of the fact that nil.to_f == 0.0
: 在您的情况下,您可以利用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
You can overload the attr_reader for priority_level
and firm_size
in Max
您可以在Max
为priority_level
和firm_size
重载attr_reader
def priority_level
read_attribute(:priority_level).nil? ? 0 : super
end
You can alternatively set default values in an after_initialize
block 您也可以在after_initialize
块中设置默认值
after_initialize do
self.priority_level = 0 if self.priority_level.nil?
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.