×

ruby · level 3 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

makes value objects that can never change.

A struct can be changed by anyone holding it: one stray tea.price = 0 and the bug spreads. Data.define(:amount, :currency) builds a class like Struct, but its objects are . They have readers and no writers, so a money amount or a colour stays exactly as it was made.

To change something, you make a new copy. hands back a fresh object with that field changed and the rest kept, leaving the original untouched. Like structs, Data objects are equal by value and accept a block of extra methods.

Money = Data.define(:amount, :currency) do
  def to_s
    "#{amount} #{currency}"
  end
end
price = Money.new(amount: 12, currency: "GBP")
sale = price.with(amount: 9)
puts price
puts sale
p price.respond_to?(:amount=)

Forgetting a field, as in Money.new(amount: 12), raises ArgumentError, so every Data object is complete.