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
2009-09-16 03:27:16
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')
2009-09-16 03:31:03
Close! I need to figure how to use "gsub" with some regex to strip the leading zeros and/or colons
2009-09-16 04:07:02
+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
2009-09-16 03:39:12
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
2009-09-16 05:52:17
No need for four different regexes and 15 lines of code to do this! A single .sub(/^[0:]*/,"") works fine!
glenn mcdonald
2009-09-16 12:05:59
+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
2009-09-16 12:08:35
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
2009-09-16 18:53:27