×

ruby · level 3 · unit 6 · lesson 1

  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 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.