Ruby - Creating Class Variables

Introduction

Class variables' names begin with @@.

class Thing 
   @@num_things = 0  
                     
   def initialize( aName, aDescription ) 
      @@num_things +=1   
   end 

end 

An instance variable is a variable that belongs to a specific object created from a class.

A class variable must be given a value when it is first declared:

@@classvar = 1000     # class variables must be initialized 

Initialization of either instance or class variables within the body of the class affects only the values stored by the class itself.

Class variables are available both to the class itself and to the objects created from that class.

Each instance variable is unique and each object has its own copy of any instance variables.

The class itself may also have its own instance variables.

Related Topic