11

Is initialize method (constructor) private or public in ruby?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Manish Shrivastava
  • 30,617
  • 13
  • 97
  • 101

2 Answers2

16

Let's see:

class Test
  def initialize; end
end

p Test.new.private_methods.sort.include?(:initialize)

This prints true, so initialize is a private method. This makes sense, it is only called by the new class method if the object is created. If we want, we can do something like this:

class Test
  def initialize
    @counter = 0
  end

  def reset!
    initialize
  end
end

Misusing the constructor like this could however lead to problems if it does more than simple variable initialization.

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
4

The initialize method in a class automatically becomes Private.

You can check it using:

puts ClassName.private_methods.sort
rohin-arka
  • 779
  • 4
  • 10
Snm Maurya
  • 1,085
  • 10
  • 12