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 end def self.new(x,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 end # A class method to report the data we collected def self.report # 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}" end end
attr
, attr_reader
, and attr_accessor
to create accessor methods for them
class << self
class << self attr_accessor :n, :totalX, :totalY end
El siguiente ejemplo muestra como crear accessors a las variables de instancia de clase:
$ cat -n creating_class_accessors.rb 1 class Tutu 2 3 class << self 4 attr_accessor :n 5 end 6 7 end 8 9 Tutu.n = 4 10 p Tutu.n 11 12 [~/point]$ ruby creating_class_accessors.rb 4
Casiano Rodriguez León 2015-01-07