What is the real need of the "initialize" method in Ruby?

3
def initialize(nome = "Anônimo", salario = 0.0)
  @nome = nome
  @salario = salario
end

To make it clear, what I can not understand is the difference between whether or not to use this method in a class and for what purpose it is eventually used.

    
asked by anonymous 07.11.2018 / 12:21

1 answer

4

If you want the functionality of it just it acts as a builder and this can be seen in What is a builder for? . But conceptually it's not exactly a builder, in practice it does, except for some ignorance of Ruby.

In fact, as the name already says, it is an initializer, so it is in it that you will do everything you need to start a new object created from this class. in it you can initialize the class variables and perform some algorithms (less common), for example open a file, call something external, etc.

As stated in the linked response above the construct is a mixed allocation and initialization. In thesis the allocation is done in a method called new , however it can not be redefined by the programmer, which it does is always default. Whenever it is called it also calls the initialize() which will do the initialization part.

If you do not use it, how will you initialize the class variables? It is possible to do in new , but it is not considered appropriate. If anything custom form in% w / o of your class the default is this method to be like this:

class Foo
    def self.new(*args, &blk)
        obj = allocate
        obj.initialize(*args, &blk)
        obj
    end
end
    
07.11.2018 / 13:07