typestar

Inheritance and super in Ruby

Subclassing with < and extending a parent method with super.

class Animal
  def initialize(name)
    @name = name
  end

  def speak
    "#{@name} makes a sound"
  end
end

class Dog < Animal
  # super calls the parent's version of the same method
  def speak
    "#{super}: woof"
  end
end

puts Animal.new("generic").speak
puts Dog.new("rex").speak

How it works

  1. Dog < Animal inherits initialize and everything else.
  2. The subclass overrides speak with its own version.
  3. super calls the parent's method and builds on its result.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
263
Tokens
58
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 39 seconds.

Type this snippet

Step 2 of 3 in Classes & modules, step 20 of 29 in Language basics.

← Previous Next →

Inheritance and super in other languages