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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Including Comparable and defining `<=>` gives you all six comparison operators for free.
  2. 2Parsing and validation belong in a factory method so instances are always well-formed.
  3. 3SemVer precedence rules — like a missing prerelease outranking one that's present — need explicit encoding, not naive string comparison.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Comparable semantic versions in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code