tags:

views:

311

answers:

4

I have a string like this: 00:11:40 or 00:02:40 how do I formated so that I can always get rid of the leading zero(s) and colon(s), so it looks like this 11:40 or 2:40

A: 

EDIT: the OP wanted this from the beginning:

seconds = 11*60+40
Time.at(seconds.to_i).gmtime.strftime('%M:%S')  # gives '11:40'

or see man strftime for more formatting options.

EDIT: incorporating all the discussion, here's the recommended approach. It removes the need for the Time call as well.

seconds = seconds.to_i
if seconds >= 60
  "#{seconds/60}:#{seconds%60}"
else
  "#{seconds}"
end
Peter
Thanks, but I need a general way of doing this. I get the string through a conversion from seconds Time.at(seconds.to_i).gmtime.strftime('%R:%S')
Close! I need to figure how to use "gsub" with some regex to strip the leading zeros and/or colons
+1  A: 

You can use something like Peter said, but would correctly be:

s = "00:11:40"
s = s[3..-1]   # 11:40

Another approach would be to use the split method:

s = "00:11:40".split(":")[1,2].join(":")

Although I find that one more confusing and complex.

Yaraher
A: 

You might want to try positive look-behind regex. Nice reference

it "should look-behind for zeros" do
time = remove_behind_zeroes("ta:da:na")
time.should be_nil

time = remove_behind_zeroes("22:43:20")
time.should == "22:43:20"

time = remove_behind_zeroes("00:12:30")
time.should == "12:30"

time = remove_behind_zeroes("00:11:40")
time.should == "11:40"

time = remove_behind_zeroes("00:02:40")
time.should == "2:40"

time = remove_behind_zeroes("00:00:26")
time.should == "26"

end

def remove_behind_zeroes(value)
exp = /(?<=00:00:)\d\d/
match = exp.match(value)
if match then return match[0] end

exp = /(?<=00:0)\d:\d\d/
match = exp.match(value)
if match then return match[0] end

exp = /(?<=00:)\d\d:\d\d/
match = exp.match(value)
if match then return match[0] end

exp = /\d\d:\d\d:\d\d/
match = exp.match(value)
if match then return match[0] end
nil

end

Gutzofter
No need for four different regexes and 15 lines of code to do this! A single .sub(/^[0:]*/,"") works fine!
glenn mcdonald
+6  A: 

We call these "leading" characters, not trailing, since they're at the beginning, but the regex for this is very easy

x.sub(/^[0:]*/,"")

That works exactly as you phrased it: starting at the beginning of the string, remove all the 0s and :s.

glenn mcdonald
Some of us are just humble students of the regex, others are just masters (you got an up from me). That's what happens when you TDD at 2200 hrs. Refactoring is left as an exercise.
Gutzofter