0
0
Rubyprogramming~5 mins

Inherited hook in Ruby

Choose your learning style9 modes available
Introduction

The inherited hook lets a class know when another class inherits from it. This helps run special code automatically whenever a new subclass is made.

You want to track or log when someone creates a subclass of your class.
You need to add or change behavior automatically in subclasses.
You want to register subclasses in a list for later use.
You want to enforce rules or initialize data when a subclass is created.
Syntax
Ruby
def self.inherited(subclass)
  # code to run when subclass inherits
end

The method inherited is a class method, so it starts with self..

The parameter subclass is the new class that inherits from the current class.

Examples
This prints the name of the new subclass when it is created.
Ruby
class Parent
  def self.inherited(subclass)
    puts "New subclass: #{subclass}"  
  end
end

class Child < Parent
end
This keeps track of all subclasses in a list and prints them.
Ruby
class Animal
  def self.inherited(subclass)
    @subclasses ||= []
    @subclasses << subclass
  end

  def self.subclasses
    @subclasses
  end
end

class Dog < Animal
end
class Cat < Animal
end

puts Animal.subclasses.inspect
Sample Program

When Car and Truck inherit from Vehicle, the inherited hook prints a message automatically.

Ruby
class Vehicle
  def self.inherited(subclass)
    puts "A new vehicle type was created: #{subclass}"
  end
end

class Car < Vehicle
end

class Truck < Vehicle
end
OutputSuccess
Important Notes

The inherited hook runs only once per subclass creation.

You can use it to set up subclass-specific data or behavior.

Summary

The inherited hook is a special class method called when a subclass is made.

It helps automate tasks related to subclass creation.

Use it to track, modify, or initialize subclasses easily.