Ruby Inheritance

christian.dinh's avatar
Published Jul 30, 2021Updated Sep 9, 2021
Contribute to Docs

In Ruby, inheritance describes the relation between classes.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours

Syntax

Inheritance is expressed when the < is used to connect the parent class, Animal, with the child class, Dog:

class Animal
def initialize(species)
@species = species
end
def species
@species
end
end
class Dog < Animal
def initialize(species, name)
super(species)
@name = name
end
end
snoop = Dog.new("Long-Beach Labrador", "Calvin")
puts snoop.species # Output: Long-Beach Labrador

The Dog class inherits all the methods from its parent Animal class, including .species.

Overriding Methods

An inheriting child class can override methods defined in its parent and replace with code specific to it:

class Animal
def initialize(species)
@species = species
end
def species
@species
end
def make_sound
"The animal made a sound that was hard to tell."
end
end
class Dog < Animal
def initialize(species, name)
super(species)
@name = name
end
def name
@name
end
def make_sound
"Bark!"
end
end
snoop = Dog.new("Long-Beach Labrador", "Calvin")
puts snoop.make_sound # Output: Bark!

The .make_sound method from Animal was overridden in Dog with a return string specific to that class.

All contributors

Contribute to Docs

Learn Ruby on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours