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:
class Dog
def bark
"Woof!"
end
end
rex = Dog.new
fido = Dog.new
puts rex.bark
puts fido.bark
p rex.class
p rex == fidoWoof!
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:
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.introduceI'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:
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.value6
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:
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
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.statementPriya: 120 (+50, -30, declined 500)
Inspecting objects
Every object can tell you about itself:
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:
class String
def shout
upcase + "!"
end
end
puts "hello".shoutHELLO!
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")?
newcreateinitializeconstructor
What does the @ in @name mean?
- A global variable
- A class variable
- An instance variable belonging to one object
- A constant
Which method does puts obj use to turn an object into text?
inspectto_sto_strprint