Ruby: OOP – code examples
Contents
Class with Inheritance
Use case: Bundle data and behavior, e.g. users, products or game characters.
class Tier
def initialize(name)
@name = name
end
def sprich
"#{@name} makes a sound"
end
end
class Hund < Tier
def sprich
"#{@name} says Woof!"
end
end
puts Hund.new("Rex").sprichinitialize is the constructor, @name an instance variable. Hund < Tier means inheritance; sprich is overridden.
Struct as a Quick Data Class
OOP#struct#data class
Use case: Small data objects without much code, e.g. coordinates, CSV rows or return values.
Punkt = Struct.new(:x, :y) do
def abstand_zum_ursprung
Math.sqrt(x**2 + y**2)
end
end
p1 = Punkt.new(3, 4)
puts p1.abstand_zum_ursprung
puts p1 == Punkt.new(3, 4)
puts p1.inspect
x, y = *p1
puts x + yStruct.new automatically creates constructor, getters/setters, ==, to_a and inspect. Output: 5.0, true, #<struct Punkt x=3, y=4>, 7.
Data.define (Immutable)
OOP#data#immutable#ruby32
Use case: Value objects like money, coordinates or DTOs that must never change.
Preis = Data.define(:betrag, :waehrung) do
def to_s
format("%.2f %s", betrag, waehrung)
end
end
p1 = Preis.new(betrag: 4.5, waehrung: "EUR")
p2 = p1.with(betrag: 5.0)
puts p1, p2
puts p1 == Preis.new(4.5, "EUR")
puts p1.frozen?Since Ruby 3.2. There are no setters; with returns a modified copy. Instances are frozen. Output: 4.50 EUR, 5.00 EUR, true, true.
Mixin with Enumerable and Comparable
OOP#module#mixin#enumerable#include
Use case: Make your own collections or values sortable and searchable without writing everything yourself.
class Warenkorb
include Enumerable
Artikel = Struct.new(:name, :preis)
def initialize
@artikel = []
end
def <<(artikel)
@artikel << artikel
self
end
def each(&block)
@artikel.each(&block)
end
end
korb = Warenkorb.new
korb << Warenkorb::Artikel.new("Coffee", 4.5) << Warenkorb::Artikel.new("Tea", 3.0)
puts korb.map(&:name).inspect
puts korb.sum(&:preis)
puts korb.min_by(&:preis).nameIt is enough to define each and include Enumerable – map, sum, min_by, sort_by and many more are immediately available. Output: ["Coffee", "Tea"], 7.5, Tea.