Ruby date is (ir)rational

Consider the following:

[DEV] main:0> Date.today
Fri, 05 Apr 2019

[DEV] main:0> (Date.today + 0.5)
Fri, 05 Apr 2019

[DEV] main:0> (Date.today + 0.5) == Date.today
false

The above was executed in a Rails application and was the reason for a quite long wtf moment. Things become more clear when I executed this:

[DEV] main:0> Date.today + 0.5 - Date.today
1/2

Turns out that the Date holds a Rational offset inside of it. This becomes more evident when you execute the above in irb:

irb(main):003:0> Date.today
=> #<date: 2019-04-05 ((2458579j,0s,0n),+0s,2299161j)>

irb(main):004:0> Date.today + 0.5
=> #<date: 2019-04-05 ((2458579j,43200s,0n),+0s,2299161j)>

Published by

Paweł Gościcki

Ruby/Rails programmer.