Ruby Date Equation Does Not Return Expected True

Why the following differences:

Time.now.end_of_day      == Time.now.end_of_day - 0.days      # false
Time.now.end_of_day.to_s == Time.now.end_of_day - 0.days.to_s # true
+5
source share
3 answers

Since the number of nanoseconds is different:

ruby-1.9.2-p180 :014 > (Time.now.end_of_day - 0.days).nsec
 => 999999000 
ruby-1.9.2-p180 :015 > Time.now.end_of_day.nsec
 => 999999998 
+4
source

As Misha said, times differ by nanoseconds. Here's an article about workarounds and fixes for this in Rails, specifically for tests like you.

Apparently the easiest approach is to round the time to seconds by adding .to_i, but there are other alternatives.

+3
source

Mischa:

docs Time:" . , , -, , .

So, your first calculation compares two Time objects that differ at the nanosecond level, but your second calculation converts both Time objects to Strings, which ignores the nanoseconds and returns true, since both String representations match.

+2
source

All Articles