0
0
Rubyprogramming~5 mins

Protected and private visibility in Ruby

Choose your learning style9 modes available
Introduction

Protected and private visibility help control who can use certain parts of your code. This keeps your program safe and organized.

When you want to hide helper methods that should not be used outside the class.
When you want to allow only related classes or objects to access certain methods.
When you want to prevent accidental changes to important data inside an object.
When you want to keep your code clean by separating public and internal details.
Syntax
Ruby
class ClassName
  private
  def private_method
    # code
  end

  protected
  def protected_method
    # code
  end
end

private methods can only be called inside the same object.

protected methods can be called by any instance of the same class or subclasses.

Examples
This method secret is private and can only be used inside the Person object.
Ruby
class Person
  private
  def secret
    "My secret"
  end
end
This method age is protected and can be called by other Person objects.
Ruby
class Person
  protected
  def age
    30
  end
end
Protected method age is used to compare ages between two Person objects.
Ruby
class Person
  def compare_age(other)
    if other.age > 20
      "Older"
    else
      "Younger"
    end
  end

  protected
  def age
    25
  end
end
Sample Program

This program shows how protected and private methods work. The age method is protected so one person can compare ages with another. The secret method is private and cannot be called outside the object.

Ruby
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def older_than?(other)
    other.age < @age
  end

  protected
  def age
    @age
  end

  private
  def secret
    "My secret info"
  end
end

person1 = Person.new("Alice", 30)
person2 = Person.new("Bob", 25)

puts person1.older_than?(person2)  # true
# puts person1.secret  # This would cause an error because secret is private
OutputSuccess
Important Notes

Trying to call a private method from outside the object will cause an error.

Protected methods allow access between objects of the same class, but not from outside.

Use private for methods only used inside the object, and protected when you want limited sharing.

Summary

Private methods are only accessible inside the same object.

Protected methods can be accessed by other objects of the same class or subclasses.

These visibility controls help keep your code safe and organized.