Andrew Kim Andrew Kim - 1 year ago 96
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

bob ="bob")

My question is the nature of initialize. Here's the thing,
is clearly a class method, but seems to me that
is an instance method(not class) that is called on the instance created WHEN the class method
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 Source

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)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download