DEV Community

Cover image for Ruby - Inheritance
Brad Bieselin
Brad Bieselin

Posted on

Ruby - Inheritance

What is Inheritance?

Ruby is an object-oriented programming language, and thus allows for inheritance. This allows the programmer to inherit the characteristics of one Ruby class into another Ruby class, which is called the superclass. Why would we want this? Well, let's be honest here. Programmers are lazy. Inheritance allows us to reuse code. Less typing, more happy.

How to understand inheritance

In our everyday lives, different things are related to each other in various ways. For example, there are many different brands of "cars" such as Honda, Toyota, Subaru, etc. Though they are different brands of cars, they are still all "cars" that have the same characteristics at their core.

A less hierarchal example would be a class of "students" and a class of "programmers" and how they interact. Not all students are programmers, but all programmers are students(if we are talking about students in a school).

This translates very well with Ruby. The use of inheritance in Ruby allows us to create classes that have shared behaviors, while also still having their differences.

Super Class and Subclass

The class which is inheriting is a subclass. A subclass has access to all of the methods of its parent, or super class. Back to our previous example, "Honda" is a subclass of "car" and so "Honda" is our subclass and "car" is our super class.
From "car" we might inherit that a car has four wheels, or a car is 6 windows. However some cars may be electric, while some may be gas. The use of inheritance in programming allows us to inherit methods that can be useful to many different subclasses, while allowing them to also contain their own unique characteristics.

How do we inherit from another class?

There is a very simple syntax to say you want to inherit from another class in Ruby. It looks like this:

class Honda < Cars
//Code goes here
end

We now have access, through inheritance, to whatever is in the "Cars" class!

We can also find the super class of a class but using the .superclass method:
Honda.superclass in our example, would return "Car" => Car

Using our inherited methods

Now that we have set up our inheritance, we can use the .super method call to refer to methods from our super class for use in our subclass!

Our example may look like this:

//Super Class
class Car
  def name
    puts "Civic"
  end
end

//Subclass
class Honda < Car
  def name
    super
  end
end

car = Honda.new
car.name

=> Civic
Enter fullscreen mode Exit fullscreen mode

Top comments (0)