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
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
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.