1. Introduction
Association refers to the relationship between multiple objects and how they relate to one another within the context of our program. For instance, considering real-world entities like authors and books, we recognize that an author can have many books, and each book has one author. This type of relationship is known as a "one-to-many" association.
In this post, we'll explore a simple association in Ruby: the relationship between Authors and Books.
2. Program Steps
1. Define an Author class that will represent an author with a list of books.
2. Define a Book class that will represent a book with an author.
3. Create methods in each class to establish and utilize the association between authors and books.
3. Code Program
# Define the Author class class Author attr_accessor :name, :books def initialize(name) @name = name @books = [] end # Add a book to the author's list of books def add_book(book) @books << book book.author = self end end # Define the Book class class Book attr_accessor :title, :author def initialize(title) @title = title @author = nil end end # Instantiate an author george = Author.new('George Orwell') # Instantiate two books book1 = Book.new('1984') book2 = Book.new('Animal Farm') # Add the books to the author george.add_book(book1) george.add_book(book2) # Display the results puts "#{george.name} wrote the books:" george.books.each { |book| puts book.title } puts "\n#{book1.title} was written by #{book1.author.name}"
Output:
George Orwell wrote the books: 1984 Animal Farm 1984 was written by George Orwell
Explanation:
1. We begin by defining two classes: Author and Book.
2. The Author class has an instance variable @books, which is an array to store the list of books written by the author.
3. The Book class has an instance variable @author that will store a reference to the author of the book.
4. The add_book method in the Author class establishes the association. When a book is added to an author, the book's author attribute is set to that author.
5. When we instantiate the Author and Book objects and call the add_book method, the association between the Author and Book is set.
6. The output showcases this association. The author's books are listed, and we can also determine the author of a particular book.
Through this example, we can see how associations between different objects can be modeled and implemented in Ruby, allowing us to capture real-world relationships in our code.
Comments
Post a Comment