Reputation: 5132
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
Upvotes: 5
Views: 184
Reputation: 3181
To expand on Mischa's answer:
From the docs on the Time object: "All times may have fraction. Be aware of this fact when comparing times with each other—times that are apparently equal when displayed may be different when compared."
So your first calculation compares two Time objects, which are different at the nanosecond level, but your second calculation converts both Time objects to Strings, which ignores the nanoseconds and returns true because both String representations match.
Upvotes: 2
Reputation: 38586
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.
Upvotes: 3
Reputation: 43298
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
Upvotes: 4