Is the initialize method a built-in method in Ruby?
Why do we have to pass arguments when we create a new object, and why it goes directly to that initialize method? And, can we create a class without an initialize method?
You can consider the relationship between the Class#new
method and each class's #initialize
method to be implemented more or less like this:
class Class
def new
instance = allocate()
instance.initialize
return instance
end
end
class Foo
def initialize
# Do nothing
end
end
You can create a class without explicitly defining an #initialize
method, because the #initialize
method is defined by default to do nothing, and its return value is always ignored (regardless of what value you return).
The arguments you pass to Class#new
are always passed directly to #initialize
in the same order and format. For example:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With