Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby class initialize (constructor) is private method or public method?

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

like image 359
Manish Shrivastava Avatar asked Jan 06 '12 14:01

Manish Shrivastava


People also ask

How do you initialize a constructor in Ruby?

Constructor with arguments In Ruby, constructors are invoked with the help of "new" keyword and a new keyword is used for creating an object of the class. The "new" keywords give an internal call to the "initialize" method and if the new has got some arguments specified, it will be passed to the initialize method.

What does initialize method do in Ruby?

The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.

Does Ruby have private methods?

A Ruby method can be:By default ALL your methods are public . Anyone can use them! But you can change this, by making a method private or protected .

How do you access a private method in Ruby?

The only way to have external access to a private method is to call it within a public method. Also, private methods can not be called with an explicit receiver, the receiver is always implicitly self. Think of private methods as internal helper methods.


1 Answers

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.

like image 154
Niklas B. Avatar answered Nov 16 '22 03:11

Niklas B.