This tutorial will guide you through creating classes, instantiating objects, and defining instance and class methods in Ruby. You’ll learn how to structure your code using object-oriented programming principles and apply these concepts to real-world scenarios.
Step 1: Understanding Classes and Objects
In Ruby, a class is a blueprint for creating objects. An object is an instance of a class. Classes define the properties (attributes) and behaviors (methods) that objects will have.
- Class: A template for objects (e.g., Car).
- Object: An instance of a class (e.g., my_car = Car.new).
# Define a simple class
class Car
end
# Create an object (instance) of the Car class
my_car = Car.newPractice Exercise
Create a class called Book. Then, instantiate an object named my_book from this class.
Show Solution
class Book
end
my_book = Book.newStep 2: Adding Attributes to a Class
Attributes are the properties of an object. In Ruby, you can define attributes using instance variables (@variable). These variables are accessible within the instance methods of the class.
- Use the initialize method to set attributes when creating an object.
class Car
def initialize(make, model)
@make = make
@model = model
end
end
my_car = Car.new('Toyota', 'Corolla')Practice Exercise
Add attributes title and author to the Book class. Instantiate an object with the title '1984' and author 'George Orwell'.
Show Solution
class Book
def initialize(title, author)
@title = title
@author = author
end
end
my_book = Book.new('1984', 'George Orwell')Step 3: Defining Instance Methods
Instance methods define the behavior of an object. They can access and modify the object's attributes.
- Use def to define a method inside the class.
class Car
def initialize(make, model)
@make = make
@model = model
end
def display_info
puts "Make: #{@make}, Model: #{@model}"
end
end
my_car = Car.new('Toyota', 'Corolla')
my_car.display_infoPractice Exercise
Add an instance method display_info to the Book class that prints the title and author of the book.
Show Solution
class Book
def initialize(title, author)
@title = title
@author = author
end
def display_info
puts "Title: #{@title}, Author: #{@author}"
end
end
my_book = Book.new('1984', 'George Orwell')
my_book.display_infoStep 4: Using Class Methods
Class methods are methods that belong to the class itself, not to individual objects. They are defined using self.method_name.
- Class methods are often used for utility functions or operations that don't depend on instance data.
class Car
def self.description
puts 'This is a Car class'
end
end
Car.descriptionPractice Exercise
Add a class method total_books to the Book class that keeps track of the total number of books created. Hint: Use a class variable @@total_books.
Show Solution
class Book
@@total_books = 0
def initialize(title, author)
@title = title
@author = author
@@total_books += 1
end
def self.total_books
@@total_books
end
end
Book.new('1984', 'George Orwell')
Book.new('To Kill a Mockingbird', 'Harper Lee')
puts "Total books: #{Book.total_books}"Step 5: Using Accessor Methods
Accessor methods allow you to read and write instance variables from outside the class. Ruby provides shortcuts: attr_reader, attr_writer, and attr_accessor.
- attr_reader: Read-only access.
- attr_writer: Write-only access.
- attr_accessor: Read and write access.
class Car
attr_accessor :make, :model
def initialize(make, model)
@make = make
@model = model
end
end
my_car = Car.new('Toyota', 'Corolla')
puts my_car.make
my_car.model = 'Camry'
puts my_car.modelPractice Exercise
Add attr_accessor for title and author to the Book class. Then, create an object and modify its title.
Show Solution
class Book
attr_accessor :title, :author
def initialize(title, author)
@title = title
@author = author
end
end
my_book = Book.new('1984', 'George Orwell')
my_book.title = 'Animal Farm'
puts my_book.titleStep 6: Inheritance in Ruby
Inheritance allows one class to inherit attributes and methods from another class. The child class (subclass) inherits from the parent class (superclass).
- Use < to define inheritance.
class Vehicle
attr_accessor :make, :model
def initialize(make, model)
@make = make
@model = model
end
end
class Car < Vehicle
def display_info
puts "Make: #{@make}, Model: #{@model}"
end
end
my_car = Car.new('Toyota', 'Corolla')
my_car.display_infoPractice Exercise
Create a subclass EBook that inherits from Book. Add an attribute file_size and a method display_file_size.
Show Solution
class Book
attr_accessor :title, :author
def initialize(title, author)
@title = title
@author = author
end
end
class EBook < Book
attr_accessor :file_size
def display_file_size
puts "File Size: #{@file_size} MB"
end
end
my_ebook = EBook.new('1984', 'George Orwell')
my_ebook.file_size = 5
my_ebook.display_file_sizeStep 7: Real-World Application: Building a Library System
Let's apply everything we've learned to build a simple library system. The system will include classes for Book, Library, and Member.
- Book: Represents a book with attributes like title and author.
- Library: Manages a collection of books and allows borrowing/returning.
- Member: Represents a library member who can borrow books.
class Book
attr_accessor :title, :author
def initialize(title, author)
@title = title
@author = author
end
end
class Library
def initialize
@books = []
end
def add_book(book)
@books << book
end
def list_books
@books.each { |book| puts "Title: #{book.title}, Author: #{book.author}" }
end
end
class Member
def initialize(name)
@name = name
@borrowed_books = []
end
def borrow_book(library, book_title)
book = library.books.find { |b| b.title == book_title }
if book
@borrowed_books << book
puts "#{@name} borrowed #{book.title}"
else
puts "Book not found."
end
end
endPractice Exercise
Extend the library system by adding a method return_book to the Member class and a method remove_book to the Library class. Test the system by borrowing and returning a book.
Show Solution
class Member
def return_book(library, book_title)
book = @borrowed_books.find { |b| b.title == book_title }
if book
@borrowed_books.delete(book)
library.add_book(book)
puts "#{@name} returned #{book.title}"
else
puts "Book not found in borrowed list."
end
end
end
class Library
def remove_book(book_title)
@books.delete_if { |b| b.title == book_title }
end
end
# Test the system
library = Library.new
book1 = Book.new('1984', 'George Orwell')
library.add_book(book1)
member = Member.new('Alice')
member.borrow_book(library, '1984')
member.return_book(library, '1984')Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.