🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Ruby Access Control — public, private, protected — Complete Beginner Guide

Ruby BasicsRuby Access Control — public, private, protected🟢 Free Lesson

Ruby Access Control — public, private, protected — Complete Beginner Guide

Learning Objectives

  • Apply public, private, and protected to methods
  • Explain why encapsulation improves design
  • Call private methods from inside the same object
  • Restrict cross-object access with protected methods
  • Use protected attributes responsibly

Why Access Control Exists

Not every method is meant for outside callers. Some steps are internal implementation details that should stay hidden. Access control lets you define clear boundaries between an object's public interface and its private machinery.

Ruby enforces access levels with the public, private, and protected keywords inside a class body.

Public Methods

Everything starts public by default. Public methods form the object's official API and can be called by any code.

class BankAccount
  def initialize(balance)
    @balance = balance
  end

  def balance
    @balance
  end

  def deposit(amount)
    @balance += amount
  end
end

account = BankAccount.new(100)
account.deposit(50)
puts account.balance

balance and deposit are intentional touchpoints for the outside world.

Private Methods

Private methods can only be called from within the object itself, typically from other instance methods using an implicit receiver. Outside code cannot invoke them.

class Report
  def generate
    puts compose
  end

  private

  def compose
    "Final report contents"
  end
end

r = Report.new
r.generate

generate calls compose internally, which works fine. Calling r.compose from outside raises a no-method error because compose is private.

Typical uses for private methods

  • Validation helpers
  • Complex calculation steps
  • Internal formatting or parsing
  • Any logic that should change freely without breaking callers

Keeping these methods private lets you refactor internals without worrying about external dependencies.

Protected Methods

Protected methods can be called by other instances of the same class, but not by unrelated outside code. They strike a middle ground between fully public and fully private.

class Employee
  def initialize(salary)
    @salary = salary
  end

  def comparable_to(other)
    puts "Mine is higher" if @salary > other.salary
  end

  protected

  def salary
    @salary
  end
end

a = Employee.new(90000)
b = Employee.new(70000)
a.comparable_to(b)

Employee a can read b's salary because both are the same class, yet external code cannot call salary directly on either object.

Comparison Table

KeywordCallable from outsideCallable from same class instancesTypical use
publicYesYesOfficial API
protectedNoYesShared internals among siblings
privateNoNoObject-only helpers

protected Attributes

You can declare attributes protected as well. That allows related objects to coordinate without exposing values to the whole program.

Remember that protected still defines a real boundary; only classes sharing the same definition cross it freely.

Designing a Small Interface

A useful exercise is to minimize the public surface of each class.

class Order
  def initialize(items)
    @items = items
  end

  def total
    sum_items
  end

  private

  def sum_items
    @items.sum
  end
end

Callers only need total. sum_items remains free to change, perhaps applying discounts or taxes later, without breaking existing code.

Common Mistakes

  • Marking everything private and then struggling to call legitimate operations
  • Leaving internal helpers public and later regretting the exposure
  • Confusing protected with private; protected allows sibling access
  • Forgetting that private applies to methods defined after the keyword in the class body

Access control statements affect all subsequent method definitions until another visibility keyword appears, so placement matters.

Designing with Access Control

Thoughtful access control is about communicating intent. Public methods form your interface contract with other developers. Private methods hide implementation details so callers do not depend on them. Protected methods allow related objects to collaborate while still hiding internals from the outside world. Applying these markers deliberately makes your APIs clearer and safer to evolve over time.

Testing Access Levels

You can verify access control in tests by asserting that calling a private method raises a no method error while public methods respond normally. This practice locks in your interface contract and catches accidental exposure of internals during refactoring. Treat access levels as part of your public API surface and enforce them with automated checks in continuous integration.

Protected Methods in Practice

Protected methods can be called by other instances of the same class or subclasses, which is useful for comparison methods that need to inspect another object internal state. This keeps the method available for cooperating objects while still hiding it from unrelated code outside the class hierarchy.

Key Takeaways

💡

  • Public methods define an object's safe external interface
  • Private methods run only inside the object that owns them
  • Protected methods allow access among instances of the same class
  • Hide helpers to keep refactoring safe and dependencies small
  • Visibility keywords apply to methods defined after them in the class

Practice Questions

  1. Write a class with one public method that calls a private helper.
  2. What error occurs when outside code calls a private method?
  3. How does protected differ from private?
  4. Why is limiting public methods considered good design?
  5. Where must the private keyword appear to affect subsequent methods?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Ruby Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement