Cover by Huw Collingbourne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Class Variables

Class methods may remind you of the class variables you used previously (that is, variables whose names begin with @@). You may recall that you used class variables in a simple adventure game (see 2adventure.rb in Attribute Readers and Writers) to keep a tally of the total number of objects in the game; each time a new Thing object was created, 1 was added to the @@num_things class variable:

class Thing
   @@num_things = 0

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

end

Unlike an instance variable (that 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required