concept instance variable in category ruby

appears as: Instce variables, n instance variable, The instce variable, An instce variable, instce variable, instce variables
The Well-Grounded Rubyist, Third Edition

This is an excerpt from Manning's book The Well-Grounded Rubyist, Third Edition.

Instance variables, which serve the purpose of storing information within individual objects, always start with a single at-sign (@) and consist thereafter of the same character set as local variables—for example, @age and @last_name. Although a local variable can’t start with an uppercase letter, an instance variable can have one in the first position after the at-sign (though it may not have a digit in this position). But usually the character after the at-sign is a lowercase letter.

Class variables, which store information per class hierarchy (again, don’t worry about the semantics at this stage), follow the same rules as instance variables, except that they start with two at-signs—for example, @@running_total.

Scope refers to the reach or visibility of identifiers, specifically variables and constants. Different types of identifiers have different scoping rules; using, say, the identifier x for a local variable in each of two method definitions has a different effect than using the global variable $x in the same two places, because local and global variables differ as to scope. In this section, we’ll consider three types of variables: global, local, and class variables. (As you’ve just seen, instance variables are self bound, rather than scope bound.) We’ll also look at the rules for resolving constants.

At its simplest, the idea behind a class variable is that it provides a storage mechanism that’s shared between a class and instances of that class, and that’s not visible to any other objects. No other entity can fill this role. Local variables don’t survive the scope change between class definitions and their inner method definitions. Globals do, but they’re also visible and mutable everywhere else in the program, not just in one class. Constants likewise: instance methods can see the constants defined in the class in which they’re defined, but the rest of the program can see those constants, too. Instance variables, of course, are visible strictly per object. A class isn’t the same object as any of its instances, and no two of its instances are the same as each other. Therefore it’s impossible, by definition, for a class to share instance variables with its instances.

Maintaining per-class state with instance variables of class objects

The alternative is to go back to basics. We need a slot where we can put a value (the total count), and it should be a different slot for every class. In other words, we need to maintain state on a per-class basis; and because classes are objects, that means on a per-object basis (for a certain group of objects, namely, class objects). And per-object state, whether the object in question is a class or something else, suggests instance variables.

The following listing shows a rewrite of the Car class in listing 5.6. Two of the class variables are still there, but @@total_count has been transformed into an instance variable.

Listing 5.7. Car with @@total_count replaced by instance variable @total_count
class Car
  @@makes = []
  @@cars = {}
  attr_reader :make
  def self.total_count
    @total_count ||= 0                #1
  end
  def self.total_count=(n)
    @total_count = n                  #2
  end
  def self.add_make(make)
    unless @@makes.include?(make)
      @@makes << make
      @@cars[make] = 0
    end
  end
  def initialize(make)
    if @@makes.include?(make)
      puts "Creating a new #{make}!"
      @make = make
      @@cars[make] += 1
      self.class.total_count += 1     #3
    else
      raise "No such make: #{make}."
    end
  end
  def make_mates
    @@cars[self.make]
  end
end


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":5,\"ch\":38},{\"line\":5,\"ch\":40}],[{\"line\":8,\"ch\":38},{\"line\":8,\"ch\":40}],[{\"line\":21,\"ch\":38},{\"line\":21,\"ch\":40}]]"}
!@%STYLE%@!

The key here is storing the counter in an instance variable belonging to the class object Car, and wrapping that instance variable in accessor methods—manually written ones, but accessor methods nonetheless. The accessor methods are Car.total_count and Car.total_count=. The first of these performs the task of initializing @total_count to zero 1. It does the initialization conditionally, using the or-equals operator, so that on the second and subsequent calls to total_count, the value of the instance variable is simply returned.