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?
Because you may want to find a difference between two DateTime
s, which may be Rational
. E.g.:
DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12)
# ⇒ (1/2)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With