marcamillion
marcamillion

Reputation: 33755

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: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
}

i.e. max.priority_level = nil.

So how do I modify my initial if statement to handle nil cases on both sides of the evaluation? i.e. if a score or max attribute is nil. Ideally, I would like it to be treated as 0 and proceed accordingly.

Upvotes: 1

Views: 311

Answers (2)

pje
pje

Reputation: 22697

You can't compare nil with a Float.

In your case you can take advantage of the fact that 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

Upvotes: 3

deefour
deefour

Reputation: 35350

You can overload the attr_reader for priority_level and firm_size in Max

def priority_level
  read_attribute(:priority_level).nil? ? 0 : super
end

You can alternatively set default values in an after_initialize block

after_initialize do
  self.priority_level = 0 if self.priority_level.nil?
end

Upvotes: 0

Related Questions