ruby · level 3 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
makes a small class with named fields in one line.
Many classes only hold a few named values: a product with a name and a price, a point with x and y. Struct.new(:name, :price) builds that class for you, with initialize, readers, writers, to_s and == already written.
Add and new takes named arguments, so Product.new(name: "Tea", price: 2) can never mix up the order. Structs have : two products with the same fields count as equal. Pass a block to Struct.new to add methods of your own.
Product = Struct.new(:name, :price, keyword_init: true) do
def label
"#{name} (#{price} pounds)"
end
end
tea = Product.new(name: "Tea", price: 2)
puts tea.label
tea.price = 3
p tea
p tea == Product.new(name: "Tea", price: 3) p shows a struct with its class name and every field, which makes debugging quick.
guess first
Two points with the same numbers. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
Point = Struct.new(:x, :y)
a = Point.new(1, 2)
b = Point.new(1, 2)
p a == b
p a.equal?(b)
p a.to_a
your turn
Your turn. Make a book with a method of its own.
Choose how many pages make a book long, then type the title of a book you like. It has 420 pages.
fix it
The seat and the price have swapped. Fix the ticket.
- The seat says 12 and the price says B7. Which order does
Ticket.newexpect? - Without
keyword_init, arguments fill the fields in order: film, then seat, then price. - Add
keyword_init: trueon line 1 and writeTicket.new(film: "Up", seat: "B7", price: 12).
nailed it
you made classes in one line. :D
Struct.new(:a, :b)builds a class with named fields.keyword_init: truemakesnewtake named arguments.- Structs with the same fields are equal.
new words in your collection
- Struct
- keyword_init
- value equality
This lesson isn’t saved. A free account remembers every lesson you finish.