Reputation: 17512
Why does this expression return false?
(Time.now - 10.hours).utc == Time.now.utc - 10.hours
Why accounts for the difference in the results? And which way is correct?
Upvotes: 2
Views: 249
Reputation: 34072
The expressions are equivalent, but when called in sequence, will not return the same result. Note:
Time.now == Time.now #=> false
Time.now - Time.now #=> Some really small negative number
If you call Time.now
twice in a row, the 2nd one happens after the first, right? Even if it's a very short amount of time after.
I wouldn't say either form is more right. If you store Time.now
and run the same comparison, you get the expected result.
t = Time.now
t.utc = 10.hours == (t - 10.hours).utc #=> true
Upvotes: 1
Reputation: 49114
(Time.now - 10.hours).utc.to_s == (Time.now.utc - 10.hours).to_s ==> true
(Time.now - 10.hours).utc - (Time.now.utc - 10.hours) ==> a small, non-zero
number. IE -1.3e-05
Note that a_time.to_s is the same as a_time.inspect and it only shows the time to the nearest second. But the internal resolution is much smaller than a sec.
Upvotes: 0
Reputation: 16241
Because they're not the same. Rubys Time.now
tracks time to a fraction of a second, the output of #to_s
just doesn't show that.
>> Time.now == Time.now
=> false
>> Time.now.to_i == Time.now.to_i
=> true
>> Time.now.to_f == Time.now.to_f
=> false
Check out the documentation for the Time
class here.
Upvotes: 0