📖 Scenario: Imagine you are building a simple program to manage different types of vehicles. You want to reuse common features like starting the engine and honking the horn, but also add specific features for cars and bikes.
🎯 Goal: You will create a base class Vehicle with common methods, then create a subclass Car that inherits from Vehicle. This will show how single inheritance works in Ruby and why Ruby uses it.
📋 What You'll Learn
Create a class called Vehicle with methods start_engine and honk
Create a subclass called Car that inherits from Vehicle
Add a method open_trunk to Car
Create an instance of Car and call all three methods
Print the outputs of the method calls
💡 Why This Matters
🌍 Real World
Single inheritance helps organize code by sharing common features in one place, like a base vehicle class for different vehicle types.
💼 Career
Understanding inheritance is key for Ruby developers to write clean, reusable, and maintainable code in real projects.
Progress0 / 4 steps
1
Create the base class Vehicle
Create a class called Vehicle with two methods: start_engine that returns the string "Engine started" and honk that returns the string "Beep beep".
Ruby
Hint
Use class Vehicle to start the class. Define methods with def and return strings.
2
Create subclass Car inheriting from Vehicle
Create a class called Car that inherits from Vehicle. Inside Car, add a method open_trunk that returns the string "Trunk opened".
Ruby
Hint
Use class Car < Vehicle to inherit. Define open_trunk method inside.
3
Create an instance of Car and call methods
Create an instance called my_car of the class Car. Call the methods start_engine, honk, and open_trunk on my_car and store their results in variables engine_status, horn_sound, and trunk_status respectively.
Ruby
Hint
Create instance with Car.new. Call methods on my_car and assign to variables.
4
Print the results
Print the values of engine_status, horn_sound, and trunk_status each on a new line.
Ruby
Hint
Use puts to print each variable on its own line.
Practice
(1/5)
1. Why does Ruby use single inheritance instead of multiple inheritance?
easy
A. To keep code simple and avoid conflicts between parent classes
B. Because Ruby does not support any form of inheritance
C. To allow a class to inherit from many classes at once
D. To make the language slower and more complex
Solution
Step 1: Understand Ruby's inheritance model
Ruby allows only one parent class for inheritance, which is called single inheritance.
Step 2: Reason why single inheritance is chosen
This design avoids conflicts that can happen when inheriting from multiple classes and keeps code easier to understand and maintain.
Final Answer:
To keep code simple and avoid conflicts between parent classes -> Option A
Quick Check:
Single inheritance avoids conflicts = D [OK]
Hint: Single inheritance avoids confusion and keeps code clean [OK]