Classes & Objects

Master Ruby classes, objects, initialize method, and instance variables for robust OOP applications.

Beginner 1 min read

Ruby Classes & Objects Mastery

Master Ruby's object-oriented programming foundation with classes and objects. Learn how to create blueprints for objects, initialize them, and work with instance variables to build robust applications.

Understanding Classes & Objects

Class: A blueprint or template that defines the structure and behavior of objects.
Object: An instance of a class - a specific realization of the blueprint with its own state and identity.

Real-World Analogy

Think of a class like a house blueprint: The blueprint (class) defines where rooms go, how many windows, etc. Each house built from that blueprint (object) is unique - different address, different paint color, different furniture inside.

Creating Your First Class

Let's start with a simple class definition and gradually build complexity.

# Basic class definition
class Person
end
# Creating objects (instances)
person1 = Person.new
person2 = Person.new
# Each object is unique
puts person1.object_id # Different ID
puts person2.object_id # Different ID
puts person1 == person2 # false - different objects

The Initialize Method

The initialize method is Ruby's constructor - it's automatically called when you create a new object with .new().

# Class with initialization
class Person
def initialize(name, age)
puts "Creating a new person..."
@name = name # Instance variable
@age = age # Instance variable
end
end
# Creating objects with parameters
alice = Person.new("Alice", 30)
bob = Person.new("Bob", 25)
# What happens when .new is called:
# 1. Ruby creates a new object
# 2. Ruby calls initialize on that object
# 3. Ruby returns the initialized object

Important: Initialize vs New

You define initialize but call .new(). Ruby automatically calls your initialize method when .new() is invoked. The initialize method should never be called directly.

Instance Variables

Instance variables (@variable) store the state of individual objects. Each object has its own copy of instance variables.

# Class with instance variables and methods
class BankAccount
def initialize(account_holder, initial_balance = 0)
@account_holder = account_holder
@balance = initial_balance
@account_number = generate_account_number
end
def deposit(amount)
if amount > 0
@balance += amount
puts "Deposited $#{amount}. New balance: $#{@balance}"
else
puts "Invalid deposit amount"
end
end
def withdraw(amount)
if amount > 0 && amount <= @balance
@balance -= amount
puts "Withdrew $#{amount}. New balance: $#{@balance}"
else
puts "Invalid withdrawal amount or insufficient funds"
end
end
def display_info
puts "Account: #{@account_number}"
puts "Holder: #{@account_holder}"
puts "Balance: $#{@balance}"
end
private
def generate_account_number
"ACC-" + rand(100000..999999).to_s
end
end
# Using the BankAccount class
alice_account = BankAccount.new("Alice Smith", 1000)
bob_account = BankAccount.new("Bob Jones")
alice_account.display_info
alice_account.deposit(500)
alice_account.withdraw(200)
bob_account.display_info
bob_account.deposit(300)
# Each object has its own instance variables
# Alice's balance doesn't affect Bob's balance

🚀 Interactive Practice

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

🎯 Key Takeaways

  • Classes are blueprints - they define structure and behavior
  • Objects are instances - unique realizations of a class
  • initialize is the constructor - called automatically by .new()
  • Instance variables (@var) store object state and are unique per object
  • Each object is independent - changing one doesn't affect others
  • Use meaningful names for classes (PascalCase) and methods (snake_case)

What are Classes and Objects?

A class is a blueprint for creating objects. An object is an instance of a class that has its own state (instance variables) and behavior (methods).

# Simple class definition
class Person
def initialize(name, age)
@name = name
@age = age
end
def introduce
\"Hi, I'm #{@name} and I'm #{@age} years old.\"
end
end
# Creating objects (instances)
person1 = Person.new(\"Alice\", 25)
person2 = Person.new(\"Bob\", 30)
puts person1.introduce
puts person2.introduce

Key Insight: In Ruby, everything is an object, including classes themselves!

The initialize Method

The initialize method is called automatically when you create a new object with the new method. It's Ruby's constructor.

# Different initialize patterns
class BankAccount
def initialize(account_number, initial_balance = 0)
@account_number = account_number
@balance = initial_balance
@transactions = []
puts \"Account #{@account_number} created with balance: $#{@balance}\"
end
def deposit(amount)
@balance += amount
@transactions << \"Deposit: $#{amount}\"
puts \"Deposited $#{amount}. New balance: $#{@balance}\"
end
def balance
@balance
end
end
# Creating accounts
account1 = BankAccount.new(\"12345\")
account2 = BankAccount.new(\"67890\", 1000)
account1.deposit(500)
puts \"Account 1 balance: $#{account1.balance}\"

Instance Variables

Instance variables (prefixed with @) store the state of each object. Each object has its own copy of instance variables.

# Instance variables example
class Car
def initialize(make, model, year)
@make = make
@model = model
@year = year
@mileage = 0
@running = false
end
def start
@running = true
puts \"#{@year} #{@make} #{@model} started\"
end
def drive(miles)
if @running
@mileage += miles
puts \"Drove #{miles} miles. Total mileage: #{@mileage}\"
else
puts \"Car is not running!\"
end
end
def info
\"#{@year} #{@make} #{@model} - #{@mileage} miles\"
end
end
car1 = Car.new(\"Toyota\", \"Camry\", 2020)
car2 = Car.new(\"Honda\", \"Civic\", 2021)
car1.start
car1.drive(50)
puts car1.info
puts car2.info

Class Methods vs Instance Methods

Instance methods operate on individual objects, while class methods operate on the class itself.

# Class methods and instance methods
class Counter
@@total_count = 0 # Class variable
def initialize
@count = 0
@@total_count += 1
end
# Instance method
def increment
@count += 1
end
def count
@count
end
# Class method
def self.total_counters
@@total_count
end
# Alternative class method syntax
class << self
def reset_total
@@total_count = 0
end
end
end
# Using class methods
puts \"Total counters: #{Counter.total_counters}\"
counter1 = Counter.new
counter2 = Counter.new
counter1.increment
counter1.increment
puts \"Counter 1: #{counter1.count}\"
puts \"Counter 2: #{counter2.count}\"
puts \"Total counters: #{Counter.total_counters}\"

Interactive Code Runner

Practice Time: Try these class and object examples and experiment with different OOP patterns.

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

Best Practices

1. Use Descriptive Names

Choose clear, descriptive names for classes, methods, and variables that express their purpose.

2. Keep Classes Focused

Each class should have a single responsibility. If a class does too many things, consider splitting it.

3. Initialize with Default Values

Provide sensible default values for optional parameters in the initialize method.

4. Use Class Methods Sparingly

Class methods should be used for operations that don't require instance data or for factory methods.

Summary

Classes and objects are the foundation of object-oriented programming in Ruby:

  • Classes are blueprints for creating objects
  • Objects are instances with their own state and behavior
  • initialize method sets up new objects
  • Instance variables store object state
  • Instance methods operate on individual objects
  • Class methods operate on the class itself

Master these concepts to build well-structured, maintainable Ruby applications.