ruby 32 lines · 7 steps

Parsing duration strings into seconds in Ruby

A parser that turns strings like "1h30m" into a total number of seconds while rejecting malformed input.

Explained by highlit
1class DurationParser
2 UNIT_SECONDS = {
3 'w' => 604_800,
4 'd' => 86_400,
5 'h' => 3_600,
6 'm' => 60,
7 's' => 1
8 }.freeze
9 
10 TOKEN = /(\d+)([wdhms])/
11 
12 class InvalidDuration < StandardError; end
13 
14 def self.parse(input)
15 normalized = input.to_s.strip.downcase
16 raise InvalidDuration, "empty duration" if normalized.empty?
17 
18 remaining = normalized.dup
19 total = 0
20 
21 remaining.gsub!(TOKEN) do
22 total += Regexp.last_match(1).to_i * UNIT_SECONDS.fetch(Regexp.last_match(2))
23 ''
24 end
25 
26 unless remaining.empty?
27 raise InvalidDuration, "unexpected characters in #{input.inspect}"
28 end
29 
30 total
31 end
32end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A frozen constant lookup table keeps unit conversions in one readable place.
  2. 2Consuming matches with a destructive gsub lets leftover characters double as a validation check.
  3. 3Raising a custom error class makes invalid input explicit rather than silently producing wrong numbers.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing duration strings into seconds in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code