Read more

Protected and Private Methods in Ruby

Dominik Schöler
March 20, 2013Software engineer at makandra GmbH

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

private

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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
Posted by Dominik Schöler to makandra dev (2013-03-20 11:41)