Can Ruby print out time difference (duration) readily?

Viewed 31411

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

12 Answers

I know this is a Ruby specific question, but if you found it like me, looking for a solution in the context of Rails, please, consider ActiveSupport::Duration and it's inspect and parts methods in particular.

For example:

start = Time.now
# => 2020-02-15 19:12:50.128638

ActiveSupport::Duration.build(Time.now - start).inspect
# => "1 minute and 52.477355 seconds"

ActiveSupport::Duration.build(Time.now - start).parts
# => {:minutes=>1, :seconds=>55.457125}

If you are not satisfied by inpect output, you can try to implement your own logic based on parts hash.

P.S. If you have a Plain Ruby project, do not forget that you can use ActiveSupport as a standalone library.

Related