Lesson 8 of 10

Classes and objects

Goal

The initialize constructor, attr and to_s

01

Explanation

A class is a template you make objects from, and each object has its own data. Product.new("Coffee", 12) creates an object and calls initialize with the same values, and in initialize you store the data in instance variables like @name = name. The @ makes the variable stay with the object instead of living only inside the method.

Code outside the class can't reach instance variables, so attr_reader :name writes a method for reading one, and attr_accessor :stock writes two methods, one for reading and one for writing. Give only as much access as you need: the price is read but never changed from outside, while the stock does change. to_s is the method that puts and interpolation use to display the object. Without it, puts product prints something like #<Product:0x000…>.

Inside methods, watch out: stock += qty without self. doesn't change the stock. It creates a local variable called stock whose value is nil, and the method crashes. So use @stock or self.stock = when you want to write to it.

02

Your task

Define a Product class that is created with Product.new(name, price, stock = 0), with name and price read-only and stock readable and writable. Then add in_stock? to return true when the stock is above zero, restock(qty) to increase it, and to_s to return the name and price in the form "Coffee — 12 SAR".

Checks

6 checks
  1. Product.new stores the name and price
  2. stock starts at zero and can be changed from outside
  3. price is read-only
  4. in_stock? returns true or false
  5. restock increases the stock
  6. to_s shows the name and price
main.rb
OutputRuby 3.4 (ruby.wasm)

Loading Ruby (about 8 MB). This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.