Protected and private visibility help control who can use certain parts of your code. This keeps your program safe and organized.
Protected and private visibility in 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.
secret is private and can only be used inside the Person object.class Person private def secret "My secret" end end
age is protected and can be called by other Person objects.class Person protected def age 30 end end
age is used to compare ages between two Person objects.class Person def compare_age(other) if other.age > 20 "Older" else "Younger" end end protected def age 25 end end
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.
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
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.
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.