Struct and Data – quick little classes
Often you want to keep a few values together: a point with x and y, a book with title and author, a snack with name and price. A hash can do it, but a typo in a key gives you a silent nil. Struct builds a small class for exactly that, in one line – its name starts with a capital letter, like every class:
Snack = Struct.new(:name, :price)
bacon = Snack.new("bacon", 4.5)
p bacon.name
p bacon.price
baconThe object knows its fields: bacon.price instead of bacon[:price], and a misspelt bacon.prize is an error at once rather than a sneaky nil. A Struct prints nicely, two with the same values are equal, and its fields can be changed:
toast = Snack.new("toast", 2.0)
p toast == Snack.new("toast", 2.0)
toast.price = 2.5
p toast.to_a
toast.to_hA block after Struct.new adds methods, just as in a class. Inside them, the fields are simply there by name. How far is it from home to the bacon shop?
Spot = Struct.new(:x, :y) do
def distance_to(other)
Math.sqrt((x - other.x)**2 + (y - other.y)**2)
end
end
home = Spot.new(0, 0)
bacon_shop = Spot.new(3, 4)
home.distance_to(bacon_shop)Sometimes being changeable is exactly what you don't want: a coin, a date or a price on a receipt should stay as it is. Data is the same idea without setters – once made, never changed. You build it with keywords, and with makes a changed copy while the original stays untouched:
Coin = Data.define(:value, :currency)
franc = Coin.new(value: 1, currency: "CHF")
p franc
five = franc.with(value: 5)
p five
franc.valueTry franc.value = 2: there is no such method. Structs and Data objects work with everything you already know – in arrays, with sum, with sort_by. &:price is short for { |s| s.price }:
menu = [Snack.new("bacon", 4.5), Snack.new("egg", 1.5), Snack.new("toast", 2.0)]
p menu.sum(&:price)
menu.sort_by(&:price).map(&:name)When an object needs a few fields and perhaps a method or two, Struct or Data is quicker than a full class. When it grows behaviour of its own, give it a class – the next lesson shows how.
Book with the fields title, author and pages, and give it a method short? that is true for books with fewer than 200 pages.# Book = Struct.new(...) do
# def short?
# ... # true for fewer than 200 pages
# end
# end
# Book.new("Why's (Poignant) Guide", "why", 176).short?
Temperature with Data.define and one field, degrees (Celsius). It gets two methods: fahrenheit (degrees · 9 / 5 + 32, so 20 °C is 68.0) and warmer(by), which returns a new Temperature that is by degrees warmer – the old one stays as it is.# Temperature = Data.define(:degrees) do
# def fahrenheit
# ... # degrees times 9, divided by 5.0, plus 32
# end
#
# def warmer(by)
# ... # a copy, by degrees warmer - with with
# end
# end
# Temperature.new(degrees: 20).warmer(5)