10

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.

4 Answers 4

16
"15:40:32.81".gsub(/:|\./, "")
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

The + isn't necessary; time.gsub(/[^\d]/,"") works just as well.
@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.
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 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.
3

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"

Comments

2
time.delete ':.'

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

time.dup.delete ':.'

1 Comment

Actually delete! would perform the delete in place. Then again this answer is old, so who knows what things where like in 2010.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.