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 the game. It does this simply by incrementing the class variable (by adding 1 to it: += 1) in its initialize method every time a new object is created:

@@num_things += 1

If you look later in the code, you will see that I have created a Map class to contain an array of rooms. This includes a version of the to_s method that prints information on each room in the array. Don’t worry about the implementation of the Map class right now; we’ll be looking at arrays and their methods in Chapter 4.

class Map

    def initialize( someRooms )
        @rooms = someRooms
    end

    def to_s
        @rooms.each {
            |a_room|
            puts(a_room)
        }
    end

end

Scroll to the code at the bottom of the file, and run the program to see how I have created and initialized all the objects and used the class variable, @@num_things, to keep a tally of all the Thing objects that have been created.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.166.149