Here, calling foo.hello works, but the private method can’t be called outside the scope of the class. Private methods can only be called implicitly - you cannot specify the object on which the method is being called.

In the code above, #leak calls the secret method correctly, but self.secret doesn’t work, because you’re explicitly setting the receiver of the method.

In case of protected methods, you can call them from the scope of any object belonging to the same class. This means that when you pass a Person object p1 as an argument to a method on another Person object p2, you can access all the protected methods of p1 within that method.

In the above example, the #older_than? method needs to access other_person’s age, but we don’t want age to be public. When age method is protected, foo.older_than?(bar) works as long as bar belongs to Person class or any of its subclasses (ie. bar.is_a?(Person) is true).

I don’t remember ever having to use protected in all these years, but it’s good to finally know where it could be used.

Further reading

Hi, I’m Nithin Bekal.
I work at Shopify in Ottawa, Canada.
Previously, co-founder of
CrowdStudio.in and
WowMakers.
Ruby is my preferred programming language,
and the topic of most of my articles here,
but I'm also a big fan of Elixir.
Tweet to me at @nithinbekal.