Is the initialization method a built-in method in Ruby?

Is the initialize method an inline method in Ruby?

Why do we have to pass arguments when creating a new object and why does it go directly to this initialization method? And can we create a class without an initialization method?

+4
source share
2 answers

You can consider the relationship between the method Class#newand each class #initialize, which will be implemented more or less as follows:

class Class
  def new
    instance = allocate()

    instance.initialize

    return instance
  end
end

class Foo
  def initialize
    # Do nothing
  end
end

#initialize, #initialize , ( , ).

, Class#new, #initialize . :

class Class
  def new (arg1, arg2, &block_arg)
    instance = allocate()

    instance.initialize(arg1, arg2, &block_arg)

    return instance
  end
end

class MyClass
  def initialize (arg1, arg2, &block_arg)
    # Do something with args
  end
end
+4

. -, . allocate ( ) - , , , . - initialize - initialize - , .

initialize , .

new - , allocate, initialize ( ) , allocate.

+3

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


All Articles