The difference between Ruby Public, Private & Protected methods

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 <mark>private</mark> 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

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.

Full Stack Heroes logo

© 2020 Full Stack Heroes