Explain it simply
Explain it simply
A class is a mould for making things. The Car class describes what every car has (a brand, the kilometres driven) and what every car can do (drive). Each time you write Car.new, the mould produces one real car, and every car carries its own brand and its own km.
This lesson covers the building blocks of a class: how to write one, where an object keeps its data, how to print it, and how to hold data that belongs to the whole class. The loose end you will notice, objects that start without data, is tied up in the initialize lesson.
Problem → Why → Solution
The problem: loose variables for every car
To track the kilometres of two cars, a variable each such as toyota_km and honda_km seems simple. But every new car adds another group of variables, and the update code has to be copied for each one, which invites slips. In the code below the author meant to add 30 to Honda, but copied the line and added toyota_km, so Honda ends at 49 instead of 37.
toyota_km = 0
honda_km = 0
toyota_km += 12
honda_km += 7
toyota_km += 30
honda_km += toyota_km # copy-paste slip: meant to add 30
puts "Toyota #{toyota_km} km, Honda #{honda_km} km" # Honda 49, not 37What a class fixes
A class describes the group of variables and the code that updates them exactly once. Every Car.new produces a fresh group, and each car is changed only by calls on that car, so one cannot disturb another. Writing toyota.drive(30) can only change Toyota, and there is no variable name left to mix up.
Core concept: class, instance variables and self
A class is a blueprint written with the class keyword. Its name starts with a capital letter and uses CamelCase (Car, ShoppingCart). Inside it you define instance methods with def, and Car.new builds a new object, called an instance, from the blueprint. Every call to new produces a separate object: two cars share the same methods but are different things, so changing one never changes the other.
State lives in instance variables, whose names start with @. An instance variable belongs to a single object, comes into existence the first time you assign to it, and is invisible from outside the object; there is no way to write car.@brand. Reading one that was never assigned does not raise an error, it returns nil. That is convenient and also a source of silent bugs, which is why the next lesson introduces initialize: it sets up every variable the moment an object is created.
To let outside code read or write an instance variable you need accessor methods, and attr_reader, attr_writer and attr_accessor generate them. attr_reader :km defines def km; @km; end, attr_writer :brand defines def brand=(value); @brand = value; end, and attr_accessor gives you both. The Getters & Setters lesson covers them in depth. Inside a method, self is the object that received the message. You may leave it off when reading, so brand means self.brand, but when assigning through a setter you must write self.brand = value, because plain brand = value creates a local variable and does not do what you meant.
puts and string interpolation call to_s on an object, while p and the REPL call inspect. If your class defines neither, to_s gives a default such as #<Car:0x000...>, where the hexadecimal number is a memory address that changes from run to run, and the default inspect adds the instance variables after it. Define to_s for the friendly text you want users and logs to see, and never write a test or a lesson that depends on the default address.
A class is also an object, so it can have its own methods and state. Methods written as def self.name belong to the class itself (Car.create). Class-level state comes in two flavours that behave very differently. A class variable such as @@sold is shared by the class and all of its subclasses. A class-level instance variable is an ordinary @name written in the class body or in a def self. method, and it belongs to that one class only. The deeper section shows why @@ so often surprises people.
- class Car describes the blueprint
- Car.new stamps out one instance
- Each instance gets its own @variables
- Methods run against the receiving object
All instances share the method code, but each object has its own separate copy of the instance variables.
General pattern
class ClassName
attr_accessor :property
def method_name(argument)
@instance_variable = argument
end
def self.class_method
end
end
object = ClassName.newclass ClassName ... end is the blueprint, and attr_accessor creates a getter and setter for a property. Inside a method, @instance_variable is the state of that one object. def self.class_method defines a method called on the class itself, and ClassName.new builds an instance.
Example: two Car instances with their own state
This Car class has an attr_accessor for brand, which can be read and written, an attr_reader for km, which can only be read, and two methods, drive and to_s. Create two cars and drive only one: the other one's km does not change.
Notice @km = (@km || 0) + distance. Before it is assigned, @km is nil, so the code substitutes 0. The next lesson's initialize removes the need for this guard.
class Car
attr_accessor :brand
attr_reader :km
def drive(distance)
@km = (@km || 0) + distance
puts "#{brand} drove #{distance} km (total #{km} km)"
end
def to_s
"#{brand}, #{km || 0} km"
end
end
car = Car.new
car.brand = "Toyota"
car.drive(12)
car.drive(30)
other = Car.new
other.brand = "Honda"
puts car
puts other
puts car.class
puts car.is_a?(Car)
puts car.equal?(other)
p other.kmCode breakdown
- accessors
attr_accessor :brandThis creates both brand and brand=, which is what lets you write car.brand = "Toyota". attr_reader :km exposes km for reading only, so car.km = 5 would raise an error.
- state
@km = (@km || 0) + distance@km belongs to this object. On the first drive it is nil, so || 0 supplies 0; on the second it already holds 12, giving 42. The Honda was never driven, so its own @km is untouched.
- to_s
"#{brand}, #{km || 0} km"puts car calls to_s, which is why it prints Toyota, 42 km. Without to_s you would see something like #<Car:0x...> with an address. The Honda's km is nil, so || 0 is used here too.
- instances
puts car.equal?(other)equal? asks whether two names refer to the very same object; car and other came from two separate Car.new calls, so the answer is false. car.class is Car and car.is_a?(Car) is true.
- nil state
p other.kmThe Honda was never driven, so @km was never assigned and the reader returns nil. That is not an error, but it is a nil that would break @km + 1.
Toyota drove 12 km (total 12 km)
Toyota drove 30 km (total 42 km)
Toyota, 42 km
Honda, 0 km
Car
true
false
nilto_s versus inspect
to_s is for people and inspect is for developers. Overriding to_s changes what puts and interpolation show, while inspect stays at its default, and that default lists the instance variables, which makes debugging comfortable. The code below replaces the address part with 0x... before printing, because the address differs on every run and an exact output cannot be written down.
class Pet
attr_accessor :name
def to_s
"Pet #{name}"
end
end
pet = Pet.new
pet.name = "Mimi"
puts pet # Pet Mimi (puts calls to_s)
puts "I own: #{pet}" # I own: Pet Mimi
puts pet.inspect.sub(/0x\h+/, "0x...") # #<Pet:0x... @name="Mimi">
class Plain
attr_accessor :name
end
plain = Plain.new
plain.name = "Mimi"
puts plain.to_s.sub(/0x\h+/, "0x...") # #<Plain:0x...> (default to_s, no variables)Note that the default to_s shows no instance variables while the default inspect does. This is what Ruby 4.0.9 printed when tested, and the address part will differ on your machine.
Class methods, constants and the @@ shared-state trap
The Ticket class below has a PRICE constant, a class-level instance variable @issued and a class variable @@sold. VipTicket < Ticket means VipTicket inherits from Ticket (it is a subclass), which the Inheritance lesson covers in detail. Look at the results: @issued is separate for Ticket and VipTicket (2 and 1), but @@sold shows 3 for both, because there is only one @@sold shared by the whole family.
class Ticket
PRICE = 500 # constant: shared, by convention never reassigned
@issued = 0 # class-level instance variable: owned by Ticket only
@@sold = 0 # class variable: shared with every subclass
def self.issue
@issued += 1
@@sold += 1
new
end
def self.issued
@issued
end
def self.sold
@@sold
end
end
class VipTicket < Ticket
@issued = 0 # each class needs its own copy of @issued
end
Ticket.issue
Ticket.issue
VipTicket.issue
puts Ticket.issued # 2
puts VipTicket.issued # 1
puts Ticket.sold # 3
puts VipTicket.sold # 3 (the same @@sold)
puts VipTicket::PRICE # 500 (constants are inherited too)Two lessons come out of this code. First, @@ is shared with every subclass, so using it as 'this class's counter' also changes other classes' numbers. Second, a class-level instance variable is not inherited: without @issued = 0 inside VipTicket, @issued += 1 would be nil + 1 and raise NoMethodError: undefined method '+' for nil. Choosing a class-level instance variable and avoiding @@ is usually the safer default.
Identity, equality and open classes
If your own class does not override ==, the default checks identity, so two objects with identical properties are still not == to each other. Writing c = a does not copy anything; it gives the same object a second name, and a change made through c is visible through a. Ruby classes are also never closed: reopening class Car and adding a method gives the new method to objects that already exist. Reopening your own class is normal, but changing built-in classes such as String can surprise other people, so be careful.
class Car
attr_accessor :brand
end
a = Car.new
b = Car.new
c = a
puts a == b # false: == defaults to identity
puts a.equal?(b) # false
puts a.equal?(c) # true: c is a second name for the same object
c.brand = "Mazda"
puts a.brand # Mazda: the change is visible through both names
class Car # reopening the class
def honk
"Beep from #{brand}"
end
end
puts a.honk # Beep from Mazda: existing objects get the new methodIn real projects
Where this shows up in real projects
Read any Rails code and you will see the class versus instance split everywhere. User.find(3) is a class method that locates one row in the database, while user.save works on that one instance. Models are written as class User < ApplicationRecord, which is inheritance layered on top of this lesson's blueprint. Outside Rails, gathering a group of related functions in a script into one small class is often enough to make it easier to read.
You do not need a class for everything. They fit things that have identity and state that changes over time, such as an order, a user or a connection. Stateless helpers are fine as plain methods in a module or as small functions. Class variables (@@) are commonly avoided in production code, and shared class-level state can become a problem when many threads touch it without protection, so look into the protective techniques later when you need them.
Common mistakes
Common mistakes
1. Calling a setter without self.
Writing def reset; brand = "none"; end makes Ruby create a new local variable called brand that vanishes when the method ends. The object's brand does not change and nothing complains. Only self.brand = "none" (or @brand = "none") changes the attribute. The mistake passes silently, which makes it hard to find.
2. Assuming @@ belongs to one class only
With @@made in class Shape and class Circle < Shape, calling Shape.make once and Circle.make once leaves Circle.made at 2, not 1, because both classes share a single @@made. For a counter per class, use a class-level instance variable (@made) and initialise it in every subclass.
3. Relying on the default to_s
Calling puts car without defining to_s prints something like #<Car:0x000...> with an address. That address differs on every run, so a test comparing the text passes only by luck, and it means nothing to users. Write a readable to_s yourself and use p with its default inspect for debugging.
4. Using an instance variable before it is set
Calling Counter.new.bump on def bump; @n += 1; end raises NoMethodError: undefined method '+' for nil, because @n was never set and reads as nil. It is not a NameError, since Ruby returns nil for an unset instance variable. The next lesson's initialize sets @n = 0 the moment the object is created.
Best practices
Best practices
- Give read-only data an attr_reader and keep attr_accessor for attributes you really want others to change.
- Write your own to_s and never show the default address-bearing text anywhere users can see it.
- For a per-class counter, prefer a class-level instance variable over @@.
- Use CamelCase for class names and snake_case for methods and variables, and keep one class per file.
Mini challenge
Mini challenge: a Book class
Write a Book class for a library. Each book has its own title, pages and pages read, and the class as a whole keeps count of how many books were created.
- Add attr_accessor :title, :pages and a pages_read method that returns 0 until something is read
- A class method Book.create(title, pages) builds a book with new and the setters and increments the class-level instance variable @created; Book.created returns it
- read(count) adds to the pages read but never beyond the total pages
- progress returns a whole-number percentage and to_s returns text like "Ruby Basics: 30/120 pages (25%)"
class Book
# TODO: @created = 0 at class level
# TODO: def self.create(title, pages) - build with new + setters, count it
# TODO: def self.created
# TODO: attr_accessor :title, :pages
# TODO: pages_read (0 until something was read)
# TODO: read(count) - never more than pages
# TODO: progress - whole-number percentage
# TODO: to_s like "Ruby Basics: 30/120 pages (25%)"
end
# TODO: create two books, read from both (one over the limit), print them,
# print the created count and whether the two books are the same objectExpected: Ruby Basics: 30/120 pages (25%) Rails Guide: 200/200 pages (100%) Books created: 2 false
Show hint
[pages_read + count, pages].min keeps @pages_read from passing pages. pages_read * 100 / pages uses integer division, so it returns 25. Inside def self.create you can call new without self, because self is the class itself there.
Show solution
class Book
@created = 0
def self.create(title, pages)
book = new
book.title = title
book.pages = pages
@created += 1
book
end
def self.created
@created
end
attr_accessor :title, :pages
def pages_read
@pages_read || 0
end
def read(count)
@pages_read = [pages_read + count, pages].min
end
def progress
pages_read * 100 / pages
end
def to_s
"#{title}: #{pages_read}/#{pages} pages (#{progress}%)"
end
end
ruby = Book.create("Ruby Basics", 120)
rails = Book.create("Rails Guide", 200)
ruby.read(30)
rails.read(150)
rails.read(100)
puts ruby
puts rails
puts "Books created: #{Book.created}"
puts ruby.equal?(rails)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class is the blueprint and Car.new stamps out one instance each time; instance variables (@name) belong to one object and read as nil until set.
- attr_reader, attr_writer and attr_accessor generate the accessors, and inside a method you call a setter with self.brand =.
- puts calls to_s and p calls inspect; the default output holds a memory address that changes per run, so write your own to_s.
- def self.method is called on the class itself, and @@ is shared with every subclass; use a class-level @ when each class needs its own value.
Official Ruby Documentation — Ruby Documentation