Variables de Instancia de Clase

  1. Classes are objects and can have instance variables just as other objects can
  2. The instance variables of a class—often called class instance variables—are not the same as class variables
  3. They are similar enough that they can often be used instead of class variables

class Point
  # Initialize our class instance variables in the class definition itself
  @n = 0              # How many points have been created
  @totalX = 0         # The sum of all X coordinates
  @totalY = 0         # The sum of all Y coordinates

  def initialize(x,y) # Initialize method 
    @x,@y = x, y      # Sets initial values for instance variables

  def,y)   # Class method to create new Point objects
    # Use the class instance variables in this class method to collect data
    @n += 1           # Keep track of how many Points have been created
    @totalX += x      # Add these coordinates to the totals
    @totalY += y

    super             # Invoke the real definition of new to create a Point
                      # More about super later in the chapter

  # A class method to report the data we collected
    # Here we use the class instance variables in a class method
    puts "Number of points created: #@n"
    puts "Average X coordinate: #{@totalX.to_f/@n}"
    puts "Average Y coordinate: #{@totalY.to_f/@n}"

  1. Because class instance variables are just instance variables of class objects, we can use attr, attr_reader, and attr_accessor to create accessor methods for them
  2. The trick, however, is to invoke these metaprogramming methods in the right context
  3. Recall that one way to define class methods uses the syntax class << self
  4. This same syntax allows us to define attribute accessor methods for class instance variables:

class << self
  attr_accessor :n, :totalX, :totalY

El siguiente ejemplo muestra como crear accessors a las variables de instancia de clase:

$ cat -n creating_class_accessors.rb 
     1  class Tutu
     3    class << self
     4        attr_accessor :n
     5    end
     7  end
     9  Tutu.n = 4
    10  p Tutu.n
[~/point]$ ruby creating_class_accessors.rb 

  1. Una desventaja de las variables de instancia de clase es que no pueden ser utilizadas directamente dentro de los métodos de instancia, mientras que las variables de clase si son accesibles.
  2. Otra desventaja es el riesgo potencial de confundirlas con variables de instancia ordinarias
  3. Aún así su uso es mas recomendable que el de las variables de clase

Casiano Rodriguez León 2015-01-07