ruby
46 lines · 8 steps
Comparable semantic versions in Ruby
A SemanticVersion class parses version strings and orders them correctly, including tricky prerelease precedence.
Explained by
highlit
1class SemanticVersion
2 include Comparable
3
4 attr_reader :major, :minor, :patch, :prerelease
5
6 def self.parse(string)
7 core, prerelease = string.strip.delete_prefix("v").split("-", 2)
8 segments = core.split(".").map { |part| Integer(part) }
9 raise ArgumentError, "invalid version: #{string}" unless segments.size == 3
10
11 new(*segments, prerelease)
12 end
13
14 def initialize(major, minor, patch, prerelease = nil)
15 @major = major
16 @minor = minor
17 @patch = patch
18 @prerelease = prerelease
19 end
20
21 def <=>(other)
22 core = [major, minor, patch] <=> [other.major, other.minor, other.patch]
23 return core unless core.zero?
24
25 compare_prerelease(other)
26 end
27
28 def to_s
29 base = "#{major}.#{minor}.#{patch}"
30 prerelease ? "#{base}-#{prerelease}" : base
31 end
32
33 private
34
35 def compare_prerelease(other)
36 return 0 if prerelease.nil? && other.prerelease.nil?
37 return 1 if prerelease.nil?
38 return -1 if other.prerelease.nil?
39
40 identifiers(prerelease) <=> identifiers(other.prerelease)
41 end
42
43 def identifiers(prerelease)
44 prerelease.split(".").map { |id| id.match?(/\A\d+\z/) ? [0, Integer(id)] : [1, id] }
45 end
46end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Including Comparable and defining `<=>` gives you all six comparison operators for free.
- 2Parsing and validation belong in a factory method so instances are always well-formed.
- 3SemVer precedence rules — like a missing prerelease outranking one that's present — need explicit encoding, not naive string comparison.
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
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
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/comparable-semantic-versions-in-ruby-explained-ruby-b657/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.