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

ruby
1
require 'date'
2
class User
3
def welcome_message
4
"Happy, #{day_of_week}"
5
end
6
7
private
8
9
def day_of_week
10
Date.today.strftime("%A")
11
end
12
end

Invite us to your inbox.

Articles, guides and interviews about web development and career progression.

Max 1-2x times per month.