Ruby - Composition Example

1. Introduction

In object-oriented programming, composition is a design principle that allows us to model real-world relationships in our programs. Instead of inheriting properties from another class, we embed an instance of another class within our class. In this post, we'll examine composition through a classic example: the relationship between a Car and its Engine.


Composition is a principle where a class embeds or references another class's objects, thus allowing it to utilize the functionalities and properties of the embedded class. The key characteristic of composition is the phrase "has a." In our example, a Car "has an" Engine.

2. Program Steps

1. Define an Engine class that represents the basic functionalities of an engine.

2. Define a Car class that will contain an instance of the Engine class.

3. Provide methods in the Car class to interact with and showcase the Engine's functionalities.

3. Code Program

# Define the Engine class
class Engine
  def start
    "Engine started!"
  def stop
    "Engine stopped!"
# Define the Car class
class Car
  def initialize
    @engine =
  def start
    @engine.start + " Car is ready to drive!"
  def stop
    @engine.stop + " Car is parked!"
# Instantiate a car and interact with it
my_car =
puts my_car.start
puts my_car.stop


Engine started! Car is ready to drive!
Engine stopped! Car is parked!


1. We first create an Engine class that has basic methods to start and stop an engine.

2. Next, we define the Car class. Instead of inheriting properties and methods from the Engine class, we embed an instance of the Engine class inside the Car class. This is done using the @engine = line in the Car's constructor.

3. In the Car class, we have start and stop methods that call the respective methods of the embedded Engine object and append some additional behavior specific to the Car.

4. When we instantiate a Car object and call its methods, the output demonstrates the combined behavior of the Car and its Engine.

This implementation demonstrates how composition can be a powerful tool to model real-world relationships in code, allowing classes to have and utilize functionalities of other classes without resorting to inheritance.