Skip to content
AgileLogics
6 min read

Classes and Objects

Prerequisites: Methods, Hashes

A class is a blueprint that describes a kind of thing: what data it holds and what it can do. An object is one actual thing built from that blueprint. This style of programming is called object-oriented programming (OOP).

Real-world analogy: a class is a cookie cutter; objects are the cookies. One cutter, many cookies — each cookie can have different icing, but they all share the same shape.

Syntax

class ClassName
  def initialize(value)
    @value = value
  end
end

object = ClassName.new(value)

Example

class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  def bark
    "#{@name} says woof!"
  end

  def describe
    "#{@name} is a #{@breed}"
  end
end

rex = Dog.new("Rex", "beagle")
luna = Dog.new("Luna", "collie")

puts rex.bark
puts luna.describe
p rex.class

Expected output

Rex says woof!
Luna is a collie
Dog

Line by line:

  • class Dog defines the class. Class names use CamelCase.
  • initialize is the constructor — Ruby calls it automatically when you write Dog.new(...), passing along the arguments.
  • @name is an instance variable. The @ means it belongs to one particular object: Rex's @name is "Rex", Luna's is "Luna". Instance variables live as long as the object does.
  • bark and describe are instance methods — things every Dog object can do.

You've been using objects all along: "hello" is an object of class String, and "hello".upcase calls one of its instance methods.

Common mistakes

  • Forgetting the @: name = name inside initialize just assigns a local variable to itself, and the object never stores the name.
  • Calling Dog.bark on the class instead of on an object. Create an object first with Dog.new.

Practice

Create a BankAccount class that takes an owner name, starts with a balance of 0, and has deposit(amount) and balance_text methods. balance_text should return "Ada has $150" after depositing 100 and 50.

Show solution
class BankAccount
  def initialize(owner)
    @owner = owner
    @balance = 0
  end

  def deposit(amount)
    @balance += amount
  end

  def balance_text
    "#{@owner} has $#{@balance}"
  end
end

account = BankAccount.new("Ada")
account.deposit(100)
account.deposit(50)
puts account.balance_text
Ada has $150