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.

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.

class B
  
  def <=>(other)
    foo <=> other.foo
  end
  
  protected
  
  attr_accessor :foo
  
end
Dominik Schöler about 8 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more