Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby date equation not returning expected truth value

Why do the following differ?

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
like image 463
Victor S Avatar asked May 01 '12 23:05

Victor S


2 Answers

Because 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 
like image 133
Mischa Avatar answered Sep 22 '22 19:09

Mischa


Like Mischa said, the times differ by nanoseconds. Here is an article on workarounds and fixes for doing this in Rails, specifically for tests like you are doing.

The seemingly most straightforward approach given is to round the times to seconds by appending .to_i, but there are other alternatives.

like image 36
Jorge Israel Peña Avatar answered Sep 22 '22 19:09

Jorge Israel Peña