5

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?

1
  • 1
    initialize: What do you mean by built in? It's a [constructor[(en.wikipedia.org/wiki/Constructor_(object-oriented_programming)): used for creating instances of a class. It's not compulsory to pass arguments to initialize. can we create a class without an initialize method: yes Commented Mar 30, 2014 at 0:50

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

The logic behind creating new objects consists of two elements. First, you need to create a new object within the memory. This is done by calling allocate method on given class (it is defined on a Class class) - it takes no parameters and its only responsibility is to get a free slot from ruby memory heap slab, place a new object in that spot and return the object. The second step is to call initialize method on this newly created object - this is why initialize is an instance method rather then a class method.

The default initialize method is part of the language and it literally does nothing and takes no params.

new method is just a handy shorthand which first calls the allocate method, and then calls the initialize method (with all the passed params) on the object returned by the allocate method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.