0
0
Rubyprogramming~15 mins

Inherited hook in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Inherited Hook in Ruby
📖 Scenario: Imagine you are creating a system to track different types of vehicles. You want to know whenever a new type of vehicle class is created that inherits from your main Vehicle class.
🎯 Goal: You will build a Ruby program that uses the inherited hook method to print a message every time a new subclass inherits from Vehicle.
📋 What You'll Learn
Create a class called Vehicle
Define an inherited method inside Vehicle that takes one argument called subclass
Inside the inherited method, print a message using puts that says: "New vehicle type created: "
Create two subclasses called Car and Truck that inherit from Vehicle
Print the messages when Car and Truck are defined
💡 Why This Matters
🌍 Real World
Using the <code>inherited</code> hook helps frameworks and libraries track subclasses automatically, such as in web frameworks or plugin systems.
💼 Career
Understanding hooks like <code>inherited</code> is useful for Ruby developers building extensible applications or working with metaprogramming.
Progress0 / 4 steps
1
Create the Vehicle class
Create a class called Vehicle with no content inside it.
Ruby
Need a hint?

Use class Vehicle and end to define the class.

2
Add the inherited hook method
Inside the Vehicle class, define a method called self.inherited that takes one parameter called subclass. Inside this method, use puts to print "New vehicle type created: " followed by the subclass name using subclass.name.
Ruby
Need a hint?

The inherited method is a class method, so use self.inherited.

3
Create subclasses Car and Truck
Create two subclasses called Car and Truck that inherit from Vehicle. Use the syntax class Car < Vehicle and class Truck < Vehicle.
Ruby
Need a hint?

Use class Car < Vehicle and class Truck < Vehicle to create subclasses.

4
Run the program to see output
Run the program and observe the output. It should print two lines: "New vehicle type created: Car" and "New vehicle type created: Truck".
Ruby
Need a hint?

Just run the program. The messages print automatically when subclasses are defined.