Inicializando un Punto

El método initialize es privado:

$ cat -n calling_initialize.rb 
     1  class Tutu
     2    def initialize(a,b)
     3      @a, @b = a,b
     4    end
     5  
     6    def titi
     7      initialize(2,3)
     8    end
     9  end
    10  if __FILE__ == $0
    11    x = Tutu.new(4,5)
    12    z = x.titi()
    13    puts z.class
    14    puts z
    15    x.initialize(4,2)
    16  end

casiano@exthost:~/LPPsrc/151012$ ruby calling_initialize.rb 
Array
2
3
calling_initialize.rb:15:in `<main>': private method `initialize' called for #<Tutu:0x8bb576c @a=2, @b=3> (NoMethodError)
casiano@exthost:~/LPPsrc/151012$

The instance variables of an object can only be accessed by the instance methods of that object. Code that is not inside an instance method cannot read or set the value of an instance variable

Aviso a los programadores Java:

casiano@exthost:~/LPPsrc/151012$ cat -n instance_variables_of_a_class.rb 
     1  class Tutu
     2    @x = 4
     3    @y = 9
     4  
     5    def initialize(x,y)
     6      @x, @y = x, y
     7    end
     8    def self.x
     9      @x
    10    end
    11  
    12    def self.y
    13      @y
    14    end
    15  
    16    def x
    17      @x
    18    end
    19  
    20    def y
    21      @y
    22    end
    23  end
    24  
    25  if __FILE__ == $0
    26    puts Tutu.x        # 4
    27    puts Tutu.y        # 9
    28    z = Tutu.new(5,7)
    29    puts z.x           # 5
    30    puts z.y           # 7
    31  end

casiano@exthost:~/LPPsrc/151012$ ruby instance_variables_of_a_class.rb 
4
9
5
7

  1. This code does not do at all what a Java programmer expects. Instance variables are always resolved in the context of self.
  2. When the initialize method is invoked, self holds an instance of the Tutu class.
  3. But the code outside of that method is executed as part of the definition of the Tutu class.
  4. When those first two assignments are executed, self refers to the Tutu class itself, not to an instance of the class.
  5. The @x and @y variables inside the initialize method are completely different from those outside it.

Casiano Rodriguez León 2015-01-07