Let's take a normal ruby class:
class Person
attr_accessor :name
def initialize name
@name = name
end
end
bob = Person.new("bob")
My question is the nature of initialize. Here's the thing, new
is clearly a class method, but seems to me that initialize
is an instance method(not class) that is called on the instance created WHEN the class method new
is called.
Do I have this right? Or can someone shed some new light? I've done some google searches and couldn't find any clarity.
When a new object is initialized (that is, when you call new
on a class) what effectively gets called is this method:
class Class
def new(*args, &block)
obj = allocate
obj.send(:initialize, *args, &block)
obj
end
end
In the standard Ruby implementation, this method is implemented in C but is well documented.
To understand what's happening here you must be aware that in Ruby, even classes are Objects (they are instances or the Class
class). Thus, when calling new
on your Person
class, you are actually calling the new
method on the instance of a Class
object.
As you can see, the Person
class (being an instance of Class
itself) brings a method to allocate memory for the new instance named bob
. After the memory is allocated, the new
method calls initialize
on the newly created instance.
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