Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the initialize method a built-in method in Ruby?

Tags:

methods

ruby

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?

like image 258
Abdou23 Avatar asked Mar 30 '14 00:03

Abdou23


1 Answers

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
like image 63
user513951 Avatar answered Sep 28 '22 07:09

user513951