Andrew Kim Andrew Kim - 1 month ago 14
Ruby Question

Ruby Class instance method def initialize: instance or class method?

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.

Answer

Then a new object is initialized (that is, when you call new on a class) this is what effectively gets called is this method:

class Class
  def new(*args, &block)
    obj = allocate
    obj.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 your Person class brings a method to allocate memory for the new instance. After the memory is allocated, the new method calls initialize on the newly created instance.

Comments