0
0
Rubyprogramming~30 mins

Why single inheritance in Ruby - See It in Action

Choose your learning style9 modes available
Understanding Single Inheritance in Ruby
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use puts to print each variable on its own line.