Ruby - Class Class Variables

Introduction

Consider the following code:

@@num_things = 0 

The two @ characters define num_things to be a class variable.

The instance variables are preceded by a single @, like @name.

Whereas each new object or instance of a class assigns its own values to its own instance variables.

All objects derived from a specific class share the same class variables.

You can use the @@num_things class variable to keep a running total of the number of Thing objects.

The scope of a class variable is within the current class, as opposed to within specific objects of that class.

Class variables start with two @ symbols (@@) as opposed to the single @ symbol of object variables.

Class variables are useful for storing information relevant to all objects of a certain class.

For example, you could store the number of objects created so far in a certain class using a class variable like so:

Demo

class Square 
  def initialize 
    if defined?(@@number_of_squares) 
      @@number_of_squares += 1 # from   w ww  . j  a va  2s.  c o  m
    else 
      @@number_of_squares = 1 
    end 
  end 

  def self.count 
    @@number_of_squares 
  end 
end 

a = Square.new 
b = Square.new 
puts Square.count

Result

Because @@number_of_squares is a class variable, it's already defined each time you create a new object.

Related Topics

Exercise