Ruby Classes

Building blocks for object-oriented programming

🏗️ What are Ruby Classes?

Classes are blueprints for creating objects in Ruby. They define the properties and behaviors that objects will have, making your code organized and reusable.


# Simple class example
class Dog
  def bark
    puts "Woof! Woof!"
  end
end

my_dog = Dog.new
my_dog.bark
                                    

Output:

Woof! Woof!

Key Class Concepts

📦

Definition

Create classes with the class keyword

class Person
end
🔧

Methods

Define behaviors inside classes

def greet
  puts "Hello!"
end
🎯

Initialize

Set up new objects with initialize

def initialize(name)
  @name = name
end
📝

Attributes

Store data in instance variables

@name = "John"
@age = 25

🔹 Creating Your First Class

Classes bundle data and methods together. Here's how to create a simple class with attributes and behaviors:

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
  
  def introduce
    puts "Hi, I'm #{@name} and I'm #{@age} years old."
  end
end

# Create a new person
person1 = Person.new("Alice", 30)
person1.introduce
                            

Output:

Hi, I'm Alice and I'm 30 years old.

🔹 Instance Variables

Instance variables (starting with @) store data unique to each object. They persist throughout the object's lifetime and are accessible across all methods:

class Car
  def initialize(brand, color)
    @brand = brand
    @color = color
  end
  
  def description
    "This is a #{@color} #{@brand}"
  end
end

my_car = Car.new("Toyota", "red")
puts my_car.description
                            

Output:

This is a red Toyota

🔹 Attribute Accessors

Ruby provides shortcuts to read and write instance variables. Use attr_reader for reading, attr_writer for writing, and attr_accessor for both:

class Book
  attr_accessor :title
  attr_reader :author
  
  def initialize(title, author)
    @title = title
    @author = author
  end
end

book = Book.new("Ruby Guide", "John Doe")
puts book.title        # Read title
book.title = "New Title"  # Write title
puts book.title
puts book.author       # Read author
                            

Output:

Ruby Guide

New Title

John Doe

🔹 Class Methods vs Instance Methods

Instance methods work on individual objects, while class methods work on the class itself. Define class methods with self:

class Calculator
  # Class method
  def self.add(a, b)
    a + b
  end
  
  # Instance method
  def multiply(a, b)
    a * b
  end
end

# Call class method directly on class
puts Calculator.add(5, 3)

# Call instance method on object
calc = Calculator.new
puts calc.multiply(5, 3)
                            

Output:

8

15

🧠 Test Your Knowledge

What method is automatically called when creating a new object?