Posted almost 6 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

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.

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

protected

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.

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

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
3 months 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