Method: Tins::Duration.parse
- Defined in:
- lib/tins/duration.rb
.parse(string, template: '%S%d+%h:%m:%s.%f') ⇒ Integer, Float
Returns the number of seconds represented by the given duration string according to the provided template format.
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/tins/duration.rb', line 16 def self.parse(string, template: '%S%d+%h:%m:%s.%f') s, t = string.to_s.dup, template.dup d, sd = 0, 1 loop do t.sub!(/\A(%[Sdhmsf%]|.)/) { |directive| case directive when '%S' then s.sub!(/\A-?/) { sd *= -1 if _1 == ?-; '' } when '%d' then s.sub!(/\A\d+/) { d += 86_400 * _1.to_i; '' } when '%h' then s.sub!(/\A\d+/) { d += 3_600 * _1.to_i; '' } when '%m' then s.sub!(/\A\d+/) { d += 60 * _1.to_i; '' } when '%s' then s.sub!(/\A\d+/) { d += _1.to_i; '' } when '%f' then s.sub!(/\A\d+/) { d += Float(?. + _1); '' } when '%%' then if s[0] == ?% s[0] = '' else raise "expected %s, got #{s.inspect}" end else if directive == s[0] s[0] = '' else raise ArgumentError, "expected #{t.inspect}, got #{s.inspect}" end end '' } or break end sd * d end |