Ruby Logo

Method Visibility & Access Modifiers

Master Ruby's access modifiers: public, private, and protected methods with practical examples and best practices.

Home Ruby Method Visibility & Access Modifiers

Method Visibility & Access Modifiers

Master Ruby's access modifiers: public, private, and protected methods with practical examples and best practices.

🚀 Interactive Practice

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

🎯 Key Takeaways

  • public: Default visibility, accessible from anywhere
  • private: Only callable within the same object
  • protected: Accessible by same class and subclasses
  • Encapsulation: Hide internal implementation details

Method Visibility & Access Modifiers

Method visibility controls how methods can be accessed in Ruby. Understanding public, private, and protected methods is essential for proper object-oriented design and encapsulation.

Understanding Method Visibility

Method Visibility: Controls who can call a method. Ruby has three levels: public (default), private, and protected.

Basic Example

# Method visibility example
class
BankAccount
def initialize(balance)
@balance = balance
end

# Public methods (default)
def deposit(amount)
@balance += amount
end

def withdraw(amount)
@balance -= amount
end

private

# Private methods
def validate_amount(amount)
amount > 0
end

protected

# Protected methods
def balance
@balance
end
end
  • Public: Can be called from anywhere (default)
  • Private: Can only be called from within the same object
  • Protected: Can be called from the same class or subclasses

Public Methods

Public Methods: The default visibility. Can be called from anywhere - outside the class, from subclasses, or from within the class itself.

Public Method Examples

# Public methods are accessible from anywhere
class
Calculator
# These are public by default
def add(a, b)
a + b
end

def subtract(a, b)
a - b
end

public
# Explicitly declare public (optional)

def multiply(a, b)
a * b
end
end

# Usage - can call from outside the class
calc = Calculator.new
puts calc.add(5, 3)
# 8
puts calc.multiply(4, 6)
# 24

Key Points:

  • Public is the default visibility for all methods
  • Can be called from anywhere - outside the class, subclasses, or within the class
  • Use public keyword to explicitly declare (optional)
  • Most interface methods should be public

Private Methods

Private Methods: Can only be called from within the same object. Cannot be called with an explicit receiver (no dot notation from outside).

Private Method Examples

# Private methods - internal implementation details
class
User
def initialize(email, password)
@email = email
@password = password
end

def authenticate(input_password)
validate_password(input_password)
# Can call private method
end

private

def validate_password(input)
@password == input
end

def encrypt_password(password)
# Complex encryption logic
password.reverse
# Simplified for example
end
end

# Usage
user = User.new("test@example.com", "secret123")
puts user.authenticate("secret123")
# true
# user.validate_password("secret123")
# Error! Private method

Key Points:

  • Cannot be called with explicit receiver (no object.private_method)
  • Can only be called from within the same object
  • Use for internal implementation details and helper methods
  • All methods after private keyword become private

Protected Methods

Protected Methods: Can be called from the same class or its subclasses. Cannot be called from outside the class hierarchy.

Protected Method Examples

# Protected methods - accessible within class hierarchy
class
Animal
def initialize(name, age)
@name = name
@age = age
end

def compare_age(other_animal)
if age > other_animal.age
# Can access protected method
"\#{@name} is older than \#{other_animal.name}"
else
"\#{@name} is younger than \#{other_animal.name}"
end
end

protected

def age
@age
end
end

class
Dog
< Animal
def dog_years
age * 7
# Can access protected method from parent
end
end

# Usage
cat = Animal.new("Whiskers", 3)
dog = Dog.new("Buddy", 2)
puts cat.compare_age(dog)
# "Whiskers is older than Buddy"
puts dog.dog_years
# 14
# puts cat.age
# Error! Protected method

Key Points:

  • Can be called from the same class or its subclasses
  • Cannot be called from outside the class hierarchy
  • Useful for methods that subclasses need but shouldn't be public
  • Less commonly used than public and private

Advanced Visibility Patterns

Advanced Patterns: Ruby provides flexible ways to control method visibility including selective visibility changes, module inclusion, and dynamic visibility control.

Selective Visibility Changes

# Selective visibility changes
class
AdvancedCalculator
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
def multiply(a, b)
a * b
end
def divide(a, b)
a / b
end
# Make only specific methods private
private
:divide
# Make specific methods protected
protected
:multiply
end

calc = AdvancedCalculator.new
puts calc.add(5, 3)
# 8 (public)
puts calc.subtract(5, 3)
# 2 (public)
# puts calc.multiply(5, 3)
# NoMethodError (protected)
# puts calc.divide(10, 2)
# NoMethodError (private)

Module Inclusion & Visibility

# Module with different visibility levels
module
Logging
def log_info(message)
puts "[INFO] \#{message}"
end
def log_error(message)
puts "[ERROR] \#{message}"
end
private
def format_timestamp
Time.now.strftime("%Y-%m-%d %H:%M:%S")
end
end

class
UserService
include Logging
def create_user(name)
log_info("Creating user: \#{name}")
# User creation logic
log_info("User created successfully")
end
end

service = UserService.new
service.create_user("Alice")
# Uses public logging methods
# service.format_timestamp
# NoMethodError (private from module)

Interactive Practice: Method Visibility

Practice Exercise

# Complete this class with proper method visibility
class
BankAccount
def initialize(account_number, initial_balance)
@account_number = account_number
@balance = initial_balance
end

# Public methods - interface for external use
def deposit(amount)
# TODO: Add validation and update balance
end

def withdraw(amount)
# TODO: Add validation and update balance
end

def balance
# TODO: Return formatted balance
end

# TODO: Add private methods for validation
# TODO: Add protected methods for account comparison
end

Challenge: Implement the BankAccount class with proper method visibility. Make validation methods private and comparison methods protected.

Best Practices & Common Pitfalls

✅ Best Practices

  • Keep the public interface minimal and focused
  • Use private for internal implementation details
  • Use protected sparingly - only when subclasses need access
  • Group methods by visibility for better readability
  • Document public methods thoroughly
  • Use descriptive names for private methods

❌ Common Pitfalls

  • Making everything public (breaks encapsulation)
  • Using protected when private would suffice
  • Forgetting that private methods can't use explicit receivers
  • Not grouping methods by visibility
  • Making internal methods public for testing
  • Overusing private methods (can make code hard to test)

Method Visibility Mastery Summary

You've Mastered Method Visibility!

Public Methods

Default visibility, accessible from anywhere

Private Methods

Internal implementation, same object only

Protected Methods

Class hierarchy access, subclasses included

Method visibility is essential for proper object-oriented design. Use it to create clean, maintainable interfaces while protecting internal implementation details.

Inheritance
Accessors & Attributes

Quick Navigation

Read Topic
Watch Video Tutorial

Related Topics

Classes → Methods → Accessors →

Back to Ruby Home

Video Tutorial

Watch and learn method visibility & access modifiers

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!