Introduction

Ruby supports a third form of encapsulation other than public and private called protected.

protected makes a method private, but within the scope of a class rather than within a single object.

For example, you were unable to directly call a private method outside the scope of that object and its methods.

However, you can call a protected method from the scope of the methods of any object that's a member of the same class:

Demo

class Person 
  def initialize(age) 
    @age = age # from   w w  w .  j  a  va 2  s  .  com
  end 

  def age 
    @age 
  end 

  def age_difference_with(other_person) 
    (self.age - other_person.age).abs 
  end 

  protected :age 
end 

fred = Person.new(34) 
chris = Person.new(25) 
puts chris.age_difference_with(fred) 
puts chris.age

Result

Here, the code uses a protected method so that the age method cannot be used directly, except within any method belonging to an object of the Person class.

Related Topic