Public, Protected, and Private Methods

In some cases, you may want to restrict the “visibility” of your methods to ensure that they cannot be called by code outside the class in which the methods occur.

This may be useful when your class defines various “utility” methods that it requires in order to perform certain functions that it does not intend for public consumption. By imposing access restrictions on those methods, you can prevent programmers from using them for their own nefarious purposes. This means you will be able to change the implementation of those methods at a later stage without having to worry you are going to break somebody else’s code.

Ruby provides three levels of method accessibility:

  • public

  • protected

  • private

As the name suggests, ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.