Variables de Clase. Atributos de la Clase

  1. Class variables are visible to, and shared by, the class methods and the instance methods of a class, and also by the class definition itself.
  2. Like instance variables, class variables are encapsulated; they can be used by the implementation of a class, but they are not visible to the users of a class.
  3. Class variables have names that begin with @@.

class Point
  # Initialize our class 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

    # Use the class variables in this instance 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
  end

  # A class method to report the data we collected
  def self.report
    # Here we use the class 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}"
  end
end

Casiano Rodriguez León 2015-01-07