Constantes

 1 class Point
  2   attr_reader :x, :y   # Define accessor methods for our instance variables
  3 
  4   include Comparable
  5   include Enumerable
  6 
  7   def initialize(x,y)
  8     @x,@y = x, y
  9   end    
 10   
 11   ORIGIN = Point.new(0, 0)
 12   E_1    = Point.new(1, 0)
 13   E_2    = Point.new(0, 1)

Inside the class definition, these constants can be referred to by their unqualified names. Outside the definition, they must be prefixed by the name of the class:

>> load "Point2.rb"
=> true
>> Point::E_1
=> #<Point:0x100589f20 @y=0, @x=1>
>> Point::E_1.x
=> 1
>> E_1
NameError: uninitialized constant E_1
  from (irb):4
>>

Puesto que las constantes crean instancias de la clase, no podemos definirlas antes de tener definida la versión correcta del método initialize:

[~/rubytesting]$ cat constant_before_initialize.rb 
class Tutu

  C = Tutu.new(5)

  def initialize(x)
   @x = x 
  end
end
Al ejecutar produce un error:
[~/rubytesting]$ ruby constant_before_initialize.rb 
constant_before_initialize.rb:3:in `initialize': wrong number of arguments(1 for 0) (ArgumentError)
  from constant_before_initialize.rb:3:in `new'
  from constant_before_initialize.rb:3:in `<class:Tutu>'
  from constant_before_initialize.rb:1:in `<main>'
Es posible definir constantes de una clase desde fuera de la misma:
>> Point::E_3 = Point.new 1, 1
=> #<Point:0x100565df0 @y=1, @x=1>

Casiano Rodriguez León 2015-06-18