Lokesh Lokesh - 4 months ago 21
Ruby Question

How to check if an array contains Float::NAN

I find this behavior rather strange

> [1, 2, 3, 'a', 'b', Float::NAN].include? Float::NAN
false


I tried this then and got surprised

> Float::NAN == Float::NAN
false


So, to check for
Float::NAN
, I had to resort to

> [1, 2, 3, 'a', 'b', Float::NAN].any? { |i| i.is_a?(Float) && i.nan? }
true


So,


  1. Is there a better way to check for
    Float::NAN
    in an array?

  2. Why is there such a weird behavior with
    Float::NAN
    ?


Answer

To check, you can use:

[1, 2, 3, 'a', 'b', Float::NAN].any?{|item| item.respond_to?(:nan?) && item.nan?}

(or try, if you use Rails)

And as for why, take a look at What is the rationale for all comparisons returning false for IEEE754 NaN values?