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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A frozen constant lookup table keeps unit conversions in one readable place.
- 2Consuming matches with a destructive gsub lets leftover characters double as a validation check.
- 3Raising a custom error class makes invalid input explicit rather than silently producing wrong numbers.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-duration-strings-into-seconds-in-ruby-explained-ruby-a8d4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.