ruby · level 3 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A lighter copy of teal. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
Colour = Data.define(:red, :green, :blue)
teal = Colour.new(red: 0, green: 128, blue: 128)
lighter = teal.with(red: 50)
p teal.red
p lighter.red
p teal == Colour.new(red: 0, green: 128, blue: 128)
your turn
Your turn. Make tomorrow's forecast from today's.
Type a city in the first blank. Fill the second with the method that makes a changed copy, and choose tomorrow's temperature in the third.
fix it
The discount crashes the program. Fix it the Data way.
- Data objects have no writers, so
amount=does not exist. How do you change one? - You never change a Data object. You make a copy with the change, using
with. - Replace lines 3 and 4 with
discounted = price.with(amount: 15), then press run.
nailed it
you made values that cannot change. :D
Data.definebuilds classes whose objects never change.withmakes a changed copy and leaves the original alone.- Immutable values cannot be broken by someone else's code.
new words in your collection
- Data
- immutable
- with
This lesson isn’t saved. A free account remembers every lesson you finish.