×

ruby · level 2 · unit 6 · lesson 4

  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

builds a new class on top of an old one.

Dogs and cats are both pets, so why write everything twice? class Dog < Pet makes Dog a of Pet. Through inheritance, a Dog gets every method Pet has, and you add only what is special about dogs.

To a method, write one with the same name in the subclass, and Ruby uses that version instead. Inside it, runs the inherited version, so you can add to it instead of starting again.

class Pet
  def describe
    "a friendly pet"
  end
end
class Dog < Pet
  def describe = "#{super} who loves walks"
end
puts Dog.new.describe
p Dog.superclass

A one-line method can skip its end: write def describe = and then the answer.