Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 395
Andrew Kim Avatar asked Oct 25 '16 19:10

Andrew Kim


1 Answers

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.

like image 90
Holger Just Avatar answered Sep 18 '22 00:09

Holger Just