Posted over 8 years ago. Visible to the public. Repeats. Linked content.

Protected and Private Methods in Ruby

In Ruby, the meaning of protected and private is different from other languages like Java. (They don't hide methods from inheriting classes.)


Private methods can only be called with implicit receiver. As soon as you specify a receiver, let it only be self, your call will be rejected.

class A def implicit private_method end def explicit self.private_method end private def private_method "Private called" end end => "Private called" => NoMethodError: private method `private_method' called for #<A:0x101538a20>


Protected methods can be called implicitly or explicitly, as long as the receiver "is_a? self.class". An object may call a protected method on another instance of the same class, as well as on an instance of a subclass. Invoking a protected method from a class method, even of the same class, is not possible. There are no protected class methods.

A use case is comparing two objects on private attributes, which would not be possible with a private attribute.

class B def <=>(other) foo <=> end protected attr_accessor :foo end

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Dominik Schöler
Last edit:
over 2 years ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more