Convert durations in Ruby - hh:mm:ss.sss to milliseconds and vice versa

ruby, time

Solution

How about this?

a=[1, 1000, 60000, 3600000]*2
ms="01:45:36.180".split(/[:\.]/).map{|time| time.to_i*a.pop}.inject(&:+)
# => 6336180
t = "%02d" % (ms / a[3]).to_s << ":" << 
    "%02d" % (ms % a[3] / a[2]).to_s << ":" << 
    "%02d" % (ms % a[2] / a[1]).to_s << "." << 
    "%03d" % (ms % a[1]).to_s
# => "01:45:36.180"

Problem

I was wondering if there is a built-in method in Ruby that allows me to convert lap times in the format of hh:mm:ss.sss to milliseconds and vice versa. Since I need to do some calculations with it, I assumed that converting to milliseconds would be the easiest way to do this. Tell me if I am wrong here :)

Original source