Lesson 7 of 8 · 10 min

Classes

class Dog
  attr_reader :name

  def initialize(name)
    @name = name
    @tricks = []
  end

  def learn(trick)
    @tricks << trick
  end

  def to_s
    "#{@name} knows #{@tricks.size} tricks"
  end
end

rex = Dog.new("Rex")
rex.learn("sit")
puts rex            # Rex knows 1 tricks
puts rex.name       # Rex
  • initialize runs when you call Dog.new(...).
  • Variables starting with @ are instance variables: each dog has its own.
  • Instance variables are private. attr_reader :name creates a method to read @name; attr_accessor creates read and write methods.
  • to_s is what puts and interpolation use.

Errors

raise signals a problem; begin ... rescue handles it:

raise ArgumentError, "Amount must be positive" if amount <= 0

Inheritance

class GuideDog < Dog
  def guide = "#{name} is guiding"     # a one-line method
end

GuideDog gets everything Dog has. super calls the parent's version of the current method.

Your task

  1. class Account: Account.new(owner) starts with a balance of 0; readers for owner and balance; deposit(amount); withdraw(amount) raising ArgumentError if there is not enough money; to_s giving "Chipo: $25".
  2. class SavingsAccount < Account with add_interest(rate), which deposits balance * rate.
main.rb
class Account
end

acct = Account.new("Chipo")

Ruby 3.4 runs right here in your browser. The first run downloads about 16 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…