TExcelTAD
Home › Ruby › Ruby Classes & Objects

Ruby Classes & Objects

Ruby is a pure object-oriented language: every value is an object, and every object is created from a class. A class is a blueprint that describes what data an object holds and what it can do. In this section you'll write your own classes.

Defining a class

A class name is written in CamelCase. Objects (instances) are created with .new:

ruby · try it yourself
class Dog
  def bark
    "Woof!"
  end
end

rex = Dog.new
fido = Dog.new
puts rex.bark
puts fido.bark
p rex.class
p rex == fido
Woof!
Woof!
Dog
false

rex and fido are two separate objects of the same class.

initialize and instance variables

new creates the object and then calls its initialize method with the arguments you gave. Instance variables, which start with @, store each object's own data:

ruby · try it yourself
class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  def introduce
    "I'm #{@name}, a #{@breed}."
  end
end

a = Dog.new("Biscuit", "beagle")
b = Dog.new("Pixel", "corgi")
puts a.introduce
puts b.introduce
I'm Biscuit, a beagle.
I'm Pixel, a corgi.

Each object has its own @name. Instance variables are private to the object: code outside the class cannot read a.@name. To expose them you write methods — see the next lesson on accessors.

State that changes

Methods can update instance variables, so objects remember what happened to them:

ruby · try it yourself
class Counter
  def initialize(start = 0)
    @count = start
  end

  def increment(by = 1)
    @count += by
    self
  end

  def value
    @count
  end
end

clicks = Counter.new
clicks.increment
clicks.increment(5)
p clicks.value

p Counter.new(10).increment.increment.value
6
12

Returning self from increment makes calls chainable.

to_s and inspect

When you puts an object, Ruby calls its to_s method; p calls inspect. Define them to control how your objects look:

ruby · try it yourself
class Temperature
  def initialize(degrees)
    @degrees = degrees
  end

  def to_s
    "#{@degrees}°C"
  end

  def inspect
    "#<Temperature #{@degrees}>"
  end
end

t = Temperature.new(21.5)
puts t
puts "Today: #{t}"
p t
p [t, Temperature.new(-3)]
21.5°C
Today: 21.5°C
#<Temperature 21.5>
[#<Temperature 21.5>, #<Temperature -3>]

A complete example

ruby · try it yourself
class BankAccount
  def initialize(owner, balance = 0)
    @owner = owner
    @balance = balance
    @history = []
  end

  def deposit(amount)
    @balance += amount
    @history << "+#{amount}"
  end

  def withdraw(amount)
    if amount > @balance
      @history << "declined #{amount}"
      return false
    end
    @balance -= amount
    @history << "-#{amount}"
    true
  end

  def statement
    "#{@owner}: #{@balance} (#{@history.join(', ')})"
  end
end

acct = BankAccount.new("Priya", 100)
acct.deposit(50)
acct.withdraw(30)
acct.withdraw(500)
puts acct.statement
Priya: 120 (+50, -30, declined 500)

Inspecting objects

Every object can tell you about itself:

ruby · try it yourself
class Plant
  def initialize(name)
    @name = name
    @water = 0
  end

  def water!
    @water += 1
  end
end

fern = Plant.new("fern")
fern.water!
p fern.instance_variables
p fern.instance_variable_get(:@water)
p fern.respond_to?(:water!)
p fern.is_a?(Plant)
p Plant.instance_methods(false)
p Plant.superclass
[:@name, :@water]
1
true
true
[:water!]
Object

Every class you write inherits from Object unless you say otherwise.

Classes are open

You can reopen a class at any time and add methods — even built-in classes. This is called monkey patching:

ruby · try it yourself
class String
  def shout
    upcase + "!"
  end
end

puts "hello".shout
HELLO!

Note: Reopening core classes is powerful but risky in real projects — two libraries might define the same method. Prefer your own classes or refinements for such additions.

Vocabulary

Term Meaning
Class Blueprint, e.g. Dog
Object / instance One concrete thing made from a class, e.g. Dog.new
Instance variable Data stored in one object, @name
Instance method Behaviour defined with def inside the class
Constructor initialize, called by new
Receiver The object a method is called on

Test yourself

Which method is called automatically by Dog.new("Rex")?

  1. new
  2. create
  3. initialize
  4. constructor

What does the @ in @name mean?

  1. A global variable
  2. A class variable
  3. An instance variable belonging to one object
  4. A constant

Which method does puts obj use to turn an object into text?

  1. inspect
  2. to_s
  3. to_str
  4. print