Understanding Object-Oriented Programming in Ruby

March 1, 2024

In this post, we will introduce the principles of object-oriented programming (OOP) in Ruby. Learners will understand classes, objects, inheritance, and polymorphism, essential concepts in OOP.

Classes and Objects

In Ruby, everything is an object. An object is a self-contained unit that consists of both data and the methods that operate on that data. Classes are used to create and define objects. They act as blueprints for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions).

<!-- Ruby class definition -->
class Car
  def initialize(make, model)
    @make = make
    @model = model
  end

  def display_details
    puts "Make: #{@make}, Model: #{@model}"
  end
end

# Create an object of class Car
my_car = Car.new('Toyota', 'Corolla')
my_car.display_details

Inheritance

Inheritance is a fundamental feature of OOP that allows a class to inherit the properties and behaviors of another class. In Ruby, a class can inherit from another class using the < symbol.

<!-- Inheritance in Ruby -->
class ElectricCar < Car
  def initialize(make, model, battery_capacity)
    super(make, model)
    @battery_capacity = battery_capacity
  end

  def display_battery_capacity
    puts "Battery Capacity: #{@battery_capacity} kWh"
  end
end

# Create an object of class ElectricCar
my_electric_car = ElectricCar.new('Tesla', 'Model S', 100)
my_electric_car.display_details
my_electric_car.display_battery_capacity

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. In Ruby, this is achieved through method overriding and duck typing.

<!-- Polymorphism in Ruby -->
class Animal
  def make_sound
    raise 'This method must be overridden in a subclass'
  end
end

class Dog < Animal
  def make_sound
    puts 'Woof!'
  end
end

class Cat < Animal
  def make_sound
    puts 'Meow!'
end

# Create an array of Animal objects
animals = [Dog.new, Cat.new]

# Iterate through the array and call make_sound method
animals.each { |animal| animal.make_sound }