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

Asked

Viewed 200 times

3

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

To clarify, what I can’t understand is the difference between using this method in a class and for what purpose it is eventually used.

1 answer

4


If you want its functionality only it acts as a constructor and this can be seen in What good is a builder?. But conceptually he’s not exactly a builder, in practice he ends up being, except for some ignorance of mine regarding 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 class variables and run some algorithms (less common), for example open a file, call something external, etc.

As stated in the reply linked above the construction is a mix of allocation and initialization. In theory the allocation is made in a method called new, but it cannot be reset by the programmer, what he does is always default. Whenever he is called also calls the initialize() that will do the boot part.

If you do not use it, how will you initialize the class variables? It is possible to do new, but it is not considered appropriate. If nothing form customized in the new of its class the default is this method to be so:

class Foo
    def self.new(*args, &blk)
        obj = allocate
        obj.initialize(*args, &blk)
        obj
    end
end

I put in the Github for future reference.

  • The big difference between the self.new and the initialize is that one is in the class scope and the other instance, respectively

  • @vnbrs good observation. Obviously you can not call the initialize() without the object already exists.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.