Ruby 可以轻松打印出时差(持续时间)吗? [英] Can Ruby print out time difference (duration) readily?

查看:15
本文介绍了Ruby 可以轻松打印出时差(持续时间)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 可以做这样的事情吗?

Can Ruby do something like this?

irb(main):001:0> start = Time.now
=> Thu Nov 05 01:02:54 -0800 2009

irb(main):002:0> Time.now - start
=> 25.239

irb(main):003:0> (Time.now - start).duration
=> "25 seconds"

(现在不存在持续时间方法)......同样,报告

(the duration method doesn't exist now)... and similarly, report

23 minutes and 35 seconds
1 hour and 33 minutes
2 days and 3 hours

(要么报告整个持续时间,最多多少秒,要么最多报告2个数字和单位(如果报告了天和小时,则无需说明多少分钟))

(either report the whole duration, up to how many seconds, or report up to 2 numbers and units (if day and hour is reported, then no need to tell how many minutes))

推荐答案

这是一个快速而简单的实现方法.为秒、分钟、小时和天设置预定义的度量.然后根据数字的大小,用这些单位输出适当的字符串.我们将扩展 Numeric 以便您可以在任何数字类(FixnumBignum,或者在您的情况下为 Float).

Here's a quick and simple way to implement this. Set predefined measurements for seconds, minutes, hours and days. Then depending on the size of the number, output the appropriate string with the those units. We'll extend Numeric so that you can invoke the method on any numeric class (Fixnum, Bignum, or in your case Float).

class Numeric
  def duration
    secs  = self.to_int
    mins  = secs / 60
    hours = mins / 60
    days  = hours / 24

    if days > 0
      "#{days} days and #{hours % 24} hours"
    elsif hours > 0
      "#{hours} hours and #{mins % 60} minutes"
    elsif mins > 0
      "#{mins} minutes and #{secs % 60} seconds"
    elsif secs >= 0
      "#{secs} seconds"
    end
  end
end

这篇关于Ruby 可以轻松打印出时差(持续时间)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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