Posted over 7 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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Dominik Schöler
Last edit:
over 1 year 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 cookies to improve usability and analyze traffic.
Accept or learn more