July 2011
Intermediate to advanced
400 pages
8h 46m
English
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
endUnlike 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 ...
Read now
Unlock full access