ruby
36 lines · 7 steps
Turning seconds into human-readable durations in Ruby
A module that converts a raw second count into phrases like "2 hours and 5 minutes ago" by greedily peeling off the largest units.
Explained by
highlit
1module DurationFormatter
2 UNITS = [
3 ['week', 604_800],
4 ['day', 86_400],
5 ['hour', 3_600],
6 ['minute', 60],
7 ['second', 1]
8 ].freeze
9
10 module_function
11
12 def humanize(seconds, max_parts: 2)
13 seconds = seconds.round
14 return 'just now' if seconds.zero?
15
16 sign = seconds.negative? ? 'ago' : nil
17 remaining = seconds.abs
18 parts = []
19
20 UNITS.each do |name, size|
21 next if remaining < size
22
23 count = remaining / size
24 remaining %= size
25 parts << pluralize(count, name)
26 break if parts.size == max_parts
27 end
28
29 phrase = parts.join(' and ')
30 sign ? "#{phrase} #{sign}" : phrase
31 end
32
33 def pluralize(count, unit)
34 "#{count} #{unit}#{'s' unless count == 1}"
35 end
36end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Ordering units from largest to smallest lets a single pass greedily decompose a quantity.
- 2Integer division and modulo together split a remainder into a count and what's left over.
- 3Capturing the sign early and reapplying it at the end keeps the core loop working on a clean absolute value.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 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/turning-seconds-into-human-readable-durations-in-ruby-explained-ruby-4602/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.