The difference between Ruby Public, Private & Protected methods
Last updated on December 20, 2021
Ruby, like many other languages, allows you to control the access control of your methods. They can either be public (you can call the from anywhere), private or protected. In Ruby, all methods are public by default, so it's up to you to make them private or protected.
An interesting fact is that private and protected methods are not that widely used in Ruby. Out of almost 200 000 lines of code that represents the Ruby standard library, private appears in the codebase about 1000 times while protected - only about 50 times.
Public Methods
As I mentioned, the default is public visibility. If a method is public, you can call it inside the class as well from that class' object.
Private methods
You can make methods private by adding private before the method definition
1require 'date'2class User3def welcome_message4"Happy, #{day_of_week}"5end67private89def day_of_week10Date.today.strftime("%A")11end12end
Level up your web development skills
Get articles, guides and interviews right in your inbox. Join a community of fellow developers.
No spam. Unsubscribe at any time.