Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does subtraction between dates return a Rational type?

Tags:

ruby

I am trying to perform subtraction operation on dates.

date_sent = Date.parse("2013-01-01") #=> Tue, 01 Jan 2013
date_now = Date.today  #=> Wed, 04 Sep 2013
days = (date_now - date_sent) #=> (246/1)

Why does date_now - date_sent return a Rational type?

like image 788
Shamith c Avatar asked Sep 04 '13 05:09

Shamith c


2 Answers

Because you may want to find a difference between two DateTimes, which may be Rational. E.g.:

DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12)
# ⇒ (1/2)
like image 44
Aleksei Matiushkin Avatar answered Oct 20 '22 00:10

Aleksei Matiushkin


It's the expected behavior. From the docs:

d - other → date or rational

Date.new(2001,2,3) - 1               #=> #<Date: 2001-02-02 ...>
Date.new(2001,2,3) - Date.new(2001)  #=> (33/1)

A rational type is used because it can express the difference exactly:

diff = DateTime.new(2001,2,3) - DateTime.new(2001,2,2,1)
#=> (23/24)

Whereas float can't:

diff.to_f
#=> 0.9583333333333334
like image 197
Stefan Avatar answered Oct 20 '22 00:10

Stefan