Ruby - Aggregation Example

1. Introduction

In object-oriented programming, relationships between objects play a crucial role in designing and modeling real-world systems. One such relationship is aggregation. In this post, we'll explore aggregation through the relationship between a Library and its Books.


Aggregation is a type of association where one class contains a collection of objects from another class but doesn't manage their lifecycle. This means the contained objects can exist independently of the container object. A key characteristic of aggregation is the phrase "has many." For instance, a Library "has many" Books, but if the library ceases to exist, the books can still exist.

2. Program Steps

1. Define a Book class to represent individual books.

2. Define a Library class that will have a collection (or list) of Book instances.

3. Provide methods in the Library class to add books and showcase the library's collection.

3. Code Program

# Define the Book class
class Book
  attr_reader :title, :author
  def initialize(title, author)
    @title = title
    @author = author
# Define the Library class
class Library
  def initialize
    @books = []
  # Add a book to the library's collection
  def add_book(book)
    @books << book
  # Display all books in the library
  def display_books
    @books.each { |book| puts "#{book.title} by #{}" }
# Create some books and add them to a library
book1 ="1984", "George Orwell")
book2 ="To Kill a Mockingbird", "Harper Lee")
library =


1984 by George Orwell
To Kill a Mockingbird by Harper Lee


1. We begin by defining a Book class, which has attributes title and author to represent individual books.

2. The Library class is designed to manage a collection of Book objects. The collection is initialized as an empty array when a Library object is created.

3. We've included an add_book method to add a Book object to the library's collection and a display_books method to showcase all the books in the collection.

4. The example shows the creation of two Book objects which are then added to a Library object. When we call display_books, the titles and authors of all the books in the library are displayed.

5. The relationship here is an example of aggregation because the Library contains multiple Book objects, but the books' existence doesn't depend on the library. Even if the Library object is deleted, the Book objects can continue to exist independently.

By employing aggregation, developers can ensure a more modular and organized codebase, as objects maintain their independence while being associated in meaningful ways.