简体   繁体   English

如何比较Float和Nil以返回有效答案?

[英]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. 即,如果scoremax属性为零。 Ideally, I would like it to be treated as 0 and proceed accordingly. 理想情况下,我希望将其视为0并相应地进行处理。

You can't compare nil with a Float . 你无法将nilFloat进行比较。

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 您可以在Maxpriority_levelfirm_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM