🎓 A1Learner
🔍
0 of 34 lessons completed

Ruby Class Methods

A class can hold methods of its own, separate from the methods its objects use. This lesson defines those class methods and tracks counts at the class level.

def self. defines a class method

kind is defined with def self., so Dog answers it directly. The dog object answers false when asked about kind.

class Dog
  attr_reader :name
  def initialize(name)
    @name = name
  end
  def self.kind
    "dog"
  end
end
puts Dog.kind
dog = Dog.new("Rex")
puts dog.respond_to?(:kind)
puts dog.name

Class methods pass to children

kingdom is written once in Animal as a class method. Dog takes it and answers with the same word.

class Animal
  def self.kingdom
    "animal"
  end
end
class Dog < Animal
end
puts Animal.kingdom
puts Dog.kingdom

A class-level count stays per class

Each class stores its own @visits value. Cat counts two visits, and Kitten counts its single visit apart.

class Cat
  @visits = 0
  def self.visit
    @visits += 1
  end
  def self.visits
    @visits
  end
end
class Kitten < Cat
  @visits = 0
end
Cat.visit
Cat.visit
Kitten.visit
puts Cat.visits
puts Kitten.visits

@@ totals are shared by the family

Every new animal adds one to @@total, whatever its class. Animal and Dog read the same shared total.

class Animal
  @@total = 0
  def initialize
    @@total += 1
  end
  def self.total
    @@total
  end
end
class Dog < Animal
end
class Cat < Animal
end
Dog.new
Cat.new
Dog.new
puts Animal.total
puts Dog.total

Example

class Vehicle
  @@built = 0
  def initialize
    @@built += 1
  end
  def self.built
    @@built
  end
  def self.label
    "vehicle"
  end
end
class Car < Vehicle
end
puts Car.label
car = Car.new
truck = Vehicle.new
puts Vehicle.built
puts Car.built

Key points

  • def self. before a name defines a method on the class itself.
  • A class method is called on the class, not on one of its objects.
  • A child class takes the class methods of its parent.
  • A value stored in @name inside a class method belongs to that one class.
  • A name starting with @@ is a class variable shared by the whole family.

In this example, Car takes the label class method from Vehicle and answers with it. Each new object adds one to the shared @@built count. Vehicle and Car then read the same total of two.

Note

A class-level @value and an object-level @value are separate stores.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does a name starting with @@ store inside a class family?