Class Variables
A few other interesting things are going on in this program. Right at the top of the Thing class you will see this:
@@num_things = 0
The two @
characters at the start of this variable name, @@num_things
, define this to be a class variable. The variables we’ve used inside classes up to now have been instance variables, 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. I have assigned 0 to the @@num_things
variable to ensure that it has a meaningful value at the outset.
Here, the @@num_things
class variable is used to keep a running total of the number of Thing objects in ...
Get The Book of Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.