We've seen in a previous article how to define classes and instances, and how to use instance variables and methods.

Class Variables

Class variables are used for data that is associated with the class rather than the instances of that class.

class Animal
  @@species = []
end

Class variables must begin with @@ and be initialized before usage, and just like with the object instances.

Class Methods

The class methods, sometimes refered to as static methods, are defined similar to the object methods but are prefixed by self..

class Animal
  @@species = []
  def self.species
    return @@species
  end
end

puts Animal.species.to_s
  []

Class methods can then be written to manipulate the class property:

class Animal
  @@species = []
  def self.species
    return @@species
  end
  def self.add(specie)
    @@species << specie
  end
end

puts Animal.species.to_s
Animal.add Animal.new
puts Animal.species.to_s
  []
  [#<Animal:0x0000561997730a58>]