Ruby: Classes & Inheritance
What you will learn
How to define classes with attr_accessor (automatic getters/setters), the initialize constructor, and Ruby's single-inheritance model.
Defining a class
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def greet
"Hi, I'm #{@name}"
end
end
alice = Person.new("Alice", 25)
puts alice.greet # Hi, I'm Alice
puts alice.name # Alice (getter from attr_accessor)
alice.age = 26 # setter
attr_accessor :name creates both name (getter) and name= (setter) methods automatically. Use attr_reader for read-only, attr_writer for write-only.
Instance variables (@name)
Variables starting with @ are instance variables — they belong to the object and persist across method calls. Unlike local variables, they default to nil if not initialized.
Inheritance
class Animal
def speak
"..."
end
end
class Dog < Animal
def speak
"Woof!"
end
end
rex = Dog.new
puts rex.speak # Woof!
Ruby supports single inheritance — a class can have only one parent (use modules for multiple inheritance).
Modules (mixins)
Modules are collections of methods that can be mixed into classes:
module Swimmable
def swim
"#{self.class} is swimming!"
end
end
class Fish
include Swimmable # adds Swimmable methods as instance methods
end
nemo = Fish.new
puts nemo.swim # Fish is swimming!
Common mistakes
- Forgetting
@before instance variable names —name = "Alice"creates a local variable, not an instance variable - Defining
getterandsettermanually — useattr_accessorinstead - Thinking
initializeis optional — it's not if you need to set initial state; the default one takes no arguments - Confusing class variables (
@@) with instance variables (@) — class variables are shared across the class hierarchy and can cause surprising behavior
Quick check below!