Why does subtraction between dates return a Rational type?

I am trying to perform a date subtraction operation.

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 date_now - date_sent returns a Rational type?

+7
ruby
source share
4 answers

This is the expected behavior. From 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 accurately express the difference:

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

While float cannot:

 diff.to_f #=> 0.9583333333333334 
+6
source share

Because of, you can find the difference between two DateTime s, which can be Rational . For example:.

 DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12) # ⇒ (1/2) 
+2
source share

This also confused me.

The difference between the days is always an integer, so why express it as rational?

This is because it is the same return type that is used to express the difference between Date and DateTime or two DateTime. Thus, you can express the difference between two points.

I personally am not sure if this is the best choice, for example:

 Time.now.to_datetime-Date.today 

returns:

 => (44150896597/86400000000) 

I think it was clearer:

 => 0.5110978639814815 
+2
source share

Because sometimes such a comparison, as shown below:

 date_sent = DateTime.parse("2013-01-01 12:00:00") # with half a day date_now = Date.today days = (date_now - date_sent) # => (491/2) 
0
source share

All Articles