为什么日期之间的减法会返回 Rational 类型? [英] why does subtraction between dates return a Rational type?

查看:34
本文介绍了为什么日期之间的减法会返回 Rational 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对日期执行减法运算.

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)

为什么 date_now - date_sent 返回 Rational 类型?

Why does date_now - date_sent return a Rational type?

推荐答案

这是预期的行为.来自 docs:

It's the expected behavior. From the docs:

d - 其他→日期或​​理性

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)

而浮动不能:

diff.to_f
#=> 0.9583333333333334

这篇关于为什么日期之间的减法会返回 Rational 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆