Inheritance in Ruby: Exploring Attributes and Methods

Introduction

Welcome back! In this part of our Ruby Class Basics Review, we’ll dive into inheritance, a core concept in Ruby’s object-oriented programming (OOP). Inheritance enables code-sharing between classes, making our code more efficient and easier to read.

This lesson covers how inheritance works in Ruby, including attribute and method inheritance, along with the super keyword to access superclass functionality. Ready to dive in? Let’s get started!

Defining Inheritance

Inheritance in Ruby allows us to create a subclass that inherits attributes and methods from a superclass. This approach is especially useful when multiple classes share common features or behaviors.

Let’s explore with a superclass named Vehicle and a subclass named Car:

Ruby
# Define the superclass 'Vehicle'
class Vehicle
  # Initialize the Vehicle with color and brand attributes
  def initialize(color, brand)
    @color = color
    @brand = brand
  end
end

# Define the subclass 'Car', inheriting from 'Vehicle'
class Car < Vehicle
  def initialize(color, brand, doors)
    # Use 'super' to call the superclass's initialize method
    super(color, brand)
    @doors = doors
  end
end

In this example, Car inherits properties from Vehicle. Ruby supports several types of inheritance, but here we’re focusing on single inheritance, where a subclass has a single superclass.

Attribute Inheritance with attr_reader

With attribute inheritance, a subclass can inherit instance variables from its superclass.

Ruby
class Artist
  attr_reader :name  # Getter for @name

  def initialize(name)
    @name = name  # Superclass's attribute
  end
end

class Musician < Artist
  attr_reader :instrument  # Getter for @instrument

  def initialize(name, instrument)
    super(name)  # Inheriting superclass's attribute
    @instrument = instrument  # Subclass's own attribute
  end
end

john = Musician.new('John Lennon', 'Guitar')
puts john.name        # Output: John Lennon
puts john.instrument  # Output: Guitar

The Musician class inherits the @name attribute from Artist, while also introducing its own attribute, @instrument. Getters can be conveniently defined using attr_reader to access instance variables of each class.

Method Inheritance

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal