tags:

views:

50

answers:

4

I have the following output:

time = 15:40:32.81

and I want to eliminate : and the . so that it looks like this:

15403281

I tried doing a time.gsub(/\:\s/'')

but that didn't work.

Thanks for your help in advance

+3  A: 
time = '15:40:32.81'
numeric_time = time.gsub(/[^0-9]+/, '')
# numeric_time will be 15403281

[^0-9] specifies a character class containing any character which is not a digit (^ at the beginning of a class negates it), which will then be replaced by an empty string (or, in other words, removed).

(Updated to replace \d with 0-9 for clarity, though they are equivalent).

Daniel Vandersluis
Thanks for all your help!
rahrahruby
The + isn't necessary; time.gsub(/[^\d]/,"") works just as well.
todb
@todb true, but it'll cause a bigger chunk of the string to be replaced at once if multiple non-numeric characters appear in a row.
Daniel Vandersluis
On such a short string, neither variation matters a whole lot. :) I also never use [^\d]. [^0-9] is only one more character and I think it lends reading clarity. I have no idea if there's a performance difference between the two.
todb
@todb As far as I know, if there is any difference it would be negligible. `\D` could have been used instead of the character class, for that matter.
Daniel Vandersluis
A: 

"15:40:32.81".gsub(/:|\./, "")

Jed Schneider
good answer, thanks
rahrahruby
+2  A: 

If you want to be fancy and use an actual time object...

time = Time.now
time.strftime("%H%M%S") + time.usec.to_s[0,2]
# returns "15151788"
todb
A: 
time.delete ':.'

But it'll edit your variable. If you don't want it:

time.dup.delete ':.'
Nakilon