The difference between initialization and self.new

Sorry, I was not sure how to explain, to explain this. What is the difference (if any) between the two code snippets below?

class Foo
  def initalize
  end
end

class Foo
  def self.new
    allocate
  end
end

Also, what is the difference between the two ways to initialize the class below:

Foo.new
Foo.allocate
+4
source share
1 answer

allocateallocates memory for the instance Foobut does not initialize .

initializecalled on an already selected object to initialize (set the initial values) the instance Foo.

The newdefault implementation performs the following functions by default:

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

. new (, C, MRI), Ruby. - Ruby, , .

, , , Foo.

initialize , , , Foo.new , Foo.allocate, , Foo.new, .

( new , , ).

+5

Source: https://habr.com/ru/post/1543921/


All Articles