ruby
51 lines · 8 steps
Parsing user-agent strings in Ruby
A small class matches a user-agent string against ordered regex tables to extract browser, version, and OS.
Explained by
highlit
1class UserAgentParser
2 BROWSERS = [
3 [/Edg\/([\d.]+)/, "Edge"],
4 [/OPR\/([\d.]+)/, "Opera"],
5 [/Chrome\/([\d.]+)/, "Chrome"],
6 [/Version\/([\d.]+).*Safari/, "Safari"],
7 [/Firefox\/([\d.]+)/, "Firefox"],
8 [/MSIE ([\d.]+)/, "Internet Explorer"]
9 ].freeze
10
11 OPERATING_SYSTEMS = [
12 [/Windows NT 10\.0/, "Windows 10"],
13 [/Windows NT 6\.3/, "Windows 8.1"],
14 [/Mac OS X ([\d_]+)/, "macOS"],
15 [/Android ([\d.]+)/, "Android"],
16 [/iPhone OS ([\d_]+)/, "iOS"],
17 [/Linux/, "Linux"]
18 ].freeze
19
20 Result = Struct.new(:browser, :browser_version, :os, keyword_init: true)
21
22 def self.parse(user_agent)
23 new(user_agent.to_s).parse
24 end
25
26 def initialize(user_agent)
27 @user_agent = user_agent
28 end
29
30 def parse
31 browser, version = match_first(BROWSERS)
32 os, = match_first(OPERATING_SYSTEMS)
33
34 Result.new(
35 browser: browser || "Unknown",
36 browser_version: version,
37 os: os || "Unknown"
38 )
39 end
40
41 private
42
43 def match_first(patterns)
44 patterns.each do |regexp, label|
45 if (m = @user_agent.match(regexp))
46 return [label, m[1]&.tr("_", ".")]
47 end
48 end
49 [nil, nil]
50 end
51end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Ordering your patterns most-specific-first avoids false matches when strings overlap, like Edge and Opera masquerading as Chrome.
- 2Returning a Struct instead of a raw hash gives callers named, self-documenting fields with almost no boilerplate.
- 3A single reusable matcher method keeps browser and OS extraction DRY by treating both as the same ordered-table problem.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
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
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
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
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-user-agent-strings-in-ruby-explained-ruby-39cb/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.