Is initialize method (constructor) private or public 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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With