Is the initialize method a built-in method in Ruby?
methods, ruby
Solution
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
Problem
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?