Limitando el Número de Instancias de una Clase

Some classes, such as those that define enumerated types, may want to strictly limit the number of instances that exist.

Classes like these need to make their new method private and also probably want to prevent copies from being made.

The following code demonstrates one way to do that:

~/rubytesting/TheRubyProgrammingLanguage/Chapter7ClassesAndModules$ cat -n LimitingTheNumberOfInstances.rb 
     1  class Season
     2    NAMES = %w{ Spring Summer Autumn Winter }
     3    INSTANCES = []
     4  
     5    def initialize(n)
     6      @n = n
     7    end
     8  
     9    def to_s
    10      NAMES[@n]
    11    end
    12  
    13    NAMES.each_with_index { |n,i|
    14      season = new(i)
    15      INSTANCES[i] = season
    16      const_set n, season
    17    }
    18  
    19    private_class_method :allocate, :new
    20    private :dup, :clone
    21  end
    22  
    23  if __FILE__ == $0
    24    puts Season::Spring 
    25    puts Season::Summer
    26    puts Season::Autumn
    27    puts Season::Winter
    28  end
El método const_set de la clase Module establece el valor asociado con el nombre pasado como primer argumento al objeto dado como segundo argumento:
>> Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0)
=> 3.14285714285714
>> Math::HIGH_SCHOOL_PI
=> 3.14285714285714

Cuando se ejecuta el programa anterior produce esta salida:

~/rubytesting/TheRubyProgrammingLanguage/Chapter7ClassesAndModules$ ruby LimitingTheNumberOfInstances.rb 
Spring
Summer
Autumn
Winter

Casiano Rodriguez León 2015-01-07