IntermediateLesson 12 of 16
Struct, Data & Pattern Matching – Ruby
Quick data classes with Struct, immutable ones with Data and pattern matching with case/in.
For small data classes you do not need 20 lines: Struct.new creates a class with attributes, constructor, ==, to_a, inspect and more. A block may add your own methods.
Punkt = Struct.new(:x, :y) do
def abstand
Math.sqrt(x**2 + y**2)
end
end
p1 = Punkt.new(3, 4)
puts p1.x, p1.abstand # 3, 5.0
p1.x = 6
puts p1.to_a.inspect # [6, 4]
puts p1 == Punkt.new(6, 4) # true
x, y = *p1
puts "#{x}/#{y}", p1.to_h.keys.inspect # 6/4, [:x, :y]
Nutzer = Struct.new(:name, :email, keyword_init: true)
n = Nutzer.new(name: "Ada", email: "ada@example.com")
puts n.inspect # #<struct Nutzer name="Ada", email="ada@example.com">Data (since Ruby 3.2) is the immutable variant: no setters, instances are frozen. You create changes with with.
Koordinate = Data.define(:lat, :lon) do
def to_s
format("%.2f, %.2f", lat, lon)
end
end
k = Koordinate.new(lat: 50.94, lon: 6.96)
k2 = k.with(lat: 51.0)
puts k, k2 # 50.94, 6.96 / 51.00, 6.96
puts Koordinate.new(50.94, 6.96) == k # true
begin
k.instance_variable_set(:@lat, 0)
rescue FrozenError => e
puts "immutable: #{e.class}"
endPattern matching (case/in, since Ruby 3.0) takes apart hashes, arrays and objects and binds variables along the way – perfect for JSON-like data:
def beschreibe(daten)
case daten
in { typ: "kreis", radius: }
"Circle with r=#{radius}"
in { typ: "rechteck", breite:, hoehe: }
"Rectangle #{breite}x#{hoehe}"
in [erstes, *rest]
"List starts with #{erstes} (+#{rest.size})"
in Integer | Float => zahl
"Number #{zahl}"
in nil
"nothing"
else
"unknown"
end
end
puts beschreibe({ typ: "kreis", radius: 2 })
puts beschreibe({ typ: "rechteck", breite: 3, hoehe: 4 })
puts beschreibe([9, 8, 7])
puts beschreibe(2.5)
puts beschreibe(nil)
puts beschreibe("x")WarningWithout
else, case/in raises a NoMatchingPatternError if nothing matches (unlike case/when, which returns nil).Tip
OpenStruct (from require "ostruct") allows arbitrary attributes at runtime, but is slow and untyped. For fixed fields, Struct and Data are almost always the better choice.