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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Ordering your patterns most-specific-first avoids false matches when strings overlap, like Edge and Opera masquerading as Chrome.
  2. 2Returning a Struct instead of a raw hash gives callers named, self-documenting fields with almost no boilerplate.
  3. 3A single reusable matcher method keeps browser and OS extraction DRY by treating both as the same ordered-table problem.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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