I have a line like this: 00:11:40 or 00:02:40 how I form so that I can always get rid of the leading zero and colon (s), so it looks like 11:40 or 2:40
We call these βleadingβ characters not final, as they are at the beginning, but the regex is very simple
x.sub(/^[0:]*/,"")
This works the way you formulated it: from the beginning of the line, delete all 0 and .s.
You can use something like Peter, but correctly:
s = "00:11:40" s = s[3..-1] # 11:40
Another approach is to use the split method:
s = "00:11:40".split(":")[1,2].join(":")
Although I find it even more confusing and complicated.
EDIT: OP wanted this from the start:
seconds = 11*60+40 Time.at(seconds.to_i).gmtime.strftime('%M:%S') # gives '11:40'
or see man strftime for more formatting options.
man strftime
EDIT: The inclusion of all discussions is recommended here. It also eliminates the need for a time challenge.
seconds = seconds.to_i if seconds >= 60 "#{seconds/60}:#{seconds%60}" else "#{seconds}" end
You might want to try the positive regex expression. Nice link
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
Many times, you can simply rely on basic conversion methods, for example, in ruby, if you had a string like β05β and you only needed 5, you would just do β05β .to_i