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

require 'date'
class User
  def welcome_message
    "Happy, #{day_of_week}"
  end

  private

  def day_of_week
    Date.today.strftime("%A")
  end
end

Invite us to your inbox.

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

Max 1-2x times per month.