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

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

问题描述

Ruby可以做这样的事情吗?

  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秒

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

  23分35秒
1小时33分
2天3小时$ b $ (报告整个持续时间,多达几秒钟,或者报告最多2个数字和单位)(如果是日期的话); b

和小时被报告,那么就不需要告诉多少分钟))

解决方案

这是一个快速简单的方法来实现。设置秒,分,小时和天的预定义测量。然后根据数字的大小,输出与这些单位相应的字符串。我们将扩展数值,以便您可以调用任何数字类( Fixnum Bignum ,或在您的情况下 Float )。

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

如果天> 0
#{days} days和#{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
结束
结束


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

(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))

解决方案

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天全站免登陆