tags:

views:

53

answers:

1

Hey! I want to convert "123456" to "00:20:34.56" where the two digits to the right of the decimal point is in hundredth of a second. So 00:00:00.99 + 00:00:00.01 = 00:00:01.00

What I have: def to_hmsc(cent) h = (cent/360000).floor cent -= h*360000 m = (cent/6000).floor cent -= m*6000 s = (cent/100).floor cent -= s*100

"#{h}:#{m}:#{s}.#{s}" end

does this: to_hmsc("123456") #=> "0:20:34.56"

Question 1: I mean,this is ruby, I find the part ' cent -=... ' rather clunky. Can you see any way to shorten the entire process?

Question 2: This has been asked a million times before, but please share whatever you've got: what's the shortest way to add leading zero to the digits. so that to_hmsc("123456") #=> "00:20:34.56"

Thanks!

+1  A: 
Time.at(123456/100.0).strftime('%H:%M:%S.%2N')
#=> "01:20:34.56"

BTW, you should be careful with data types in Ruby, as it is strong-typed language. You can't pass a string to a method and expect it to work with it as it is a number.

Zero padding can be done in multiple ways. Usually, it is performed when formatting strings:

"%04d" % 12
#=> "0012"

Take a look at sprintf documentation for full reference.

PS. It seems that %2N doesn't work in Ruby <= 1.8.7. So here's the ugly version:

t=Time.at(123456/100.0)
'%02d:%02d:%02d.%02d' % [t.hour, t.min, t.sec, t.usec/10000]
#=> "01:20:34.56"
Mladen Jablanović
Hey Mladen! The part where you mentioned Ruby being a strong-typed language, you meant the 'cent' passed should be treated with .to_i first, is this right?Did you tried out the %2N in Time.at(123456/100.0).strftime('%H:%M:%S.%2N') and got it to work in Ruby >=1.9? I don't have 1.9 here installed..:(
Nik
Right, either to `to_i` it first, or to have it as a number beforehand (I don't know where do you get it from). And yes, I tried `%2N` in 1.9.1, it worked, then I checked 1.8.7, it didn't.
Mladen Jablanović
Got it! Thanks for the help!
Nik