Ruby: Public, Private and Protected(method Visibility)

sanju yadav
Sep 4, 2018 · 2 min read

Public, Private and protected is used to define the accessibility of methods in a class.

Public:

By default, every method is public in a class. Public methods can be accessible by anyone using class object.

public methods

Private:

Private methods are not accessible outside the scope of the class. ‘private’ keyword is used to define private methods in a class.

private methods

Protected:

Protected methods can be called within the scope of class by mentioning the explicit receiver. Protected methods behave like normal public methods inside the scope of class and like private methods outside the scope of the class. ‘protected’ keyword is used to define protected methods in class.

protected methods

How to call private/protected methods outside the scope of class?

We can use ‘send’ method to call private/protected methods from outside the scope of the class. ‘send’ eliminates the methods scope, due to which we can use send to call private/protected methods.

send use to call private methods
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade