Bird
Raised Fist0
Rubyprogramming~10 mins

Protected and private visibility in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Protected and private visibility
Define Class with Methods
↓
Call Public Method
→Works: Accessible Anywhere
↓
Call Protected Method
→Works: Accessible within class and subclasses, and between instances
↓
Call Private Method
→Works: Accessible only within the defining class, no explicit receiver
↓
Attempt Outside Access
↓
Error if Protected/Private Accessed Improperly
Shows how Ruby controls method access: public methods are open, protected methods are accessible within class and subclasses, private methods only inside the class without explicit receiver.
Execution Sample
Ruby
class Person
  def public_info
    'Public info'
  end

  protected
  def protected_info
    'Protected info'
  end

  private
  def private_info
    'Private info'
  end
end

p = Person.new
puts p.public_info
puts p.protected_info # Error
puts p.private_info   # Error
Defines a class with public, protected, and private methods and tries to call them from outside.
Execution Table
StepActionMethod CalledAccess CheckResult/Output
1Create instance p--Person object created
2Call p.public_infopublic_infoPublic method, accessible'Public info' printed
3Call p.protected_infoprotected_infoProtected method, called from outsideError: protected method called
4Call p.private_infoprivate_infoPrivate method, called with explicit receiverError: private method called
5End of program--Execution stops due to errors
💡 Execution stops because protected and private methods cannot be called with explicit receiver from outside.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
pnilPerson instancePerson instancePerson instancePerson instancePerson instance
Key Moments - 3 Insights
Why does calling p.protected_info cause an error?
Because protected methods cannot be called with an explicit receiver from outside the class, as shown in execution_table step 3.
Why can't we call p.private_info even though p is an instance of the class?
Private methods cannot be called with an explicit receiver, even if it's the same class instance, as shown in execution_table step 4.
Can protected methods be called between instances of the same class?
Yes, protected methods can be called between instances of the same class or subclasses, but not from outside, which is why step 3 fails.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when calling p.public_info at step 2?
AError: private method called
B'Public info' printed
CError: protected method called
DNo output
💡 Hint
Check execution_table row with Step 2 for method call and result.
At which step does the program raise an error due to calling a private method with an explicit receiver?
AStep 4
BStep 2
CStep 3
DStep 1
💡 Hint
Look at execution_table rows for private_info call and error.
If we call protected_info from inside another method of the same class without an explicit receiver, what would happen?
AIt would return nil
BIt would raise an error
CIt would work and return 'Protected info'
DIt would call private_info instead
💡 Hint
Recall that protected methods are accessible within the class and subclasses without explicit receiver.
Concept Snapshot
Ruby method visibility:
- public: accessible anywhere
- protected: accessible within class, subclasses, and between instances
- private: accessible only inside class, no explicit receiver
Calling protected/private methods with explicit receiver outside class causes error.
Full Transcript
This example shows how Ruby controls access to methods using public, protected, and private keywords. Public methods can be called from anywhere, so calling p.public_info works fine. Protected methods can only be called within the class or subclasses, or between instances of the same class, but not from outside with an explicit receiver, so p.protected_info causes an error. Private methods are even more restricted; they cannot be called with an explicit receiver, even from the same class instance, so p.private_info also causes an error. Understanding these rules helps avoid access errors in Ruby programs.

Practice

(1/5)
1. Which statement best describes a private method in Ruby?
easy
A. It can be accessed from anywhere in the program.
B. It can only be called within the same object, not even by other instances of the same class.
C. It can be called by any object of the same class or its subclasses.
D. It is accessible only from outside the class.

Solution

  1. Step 1: Understand private method access

    Private methods in Ruby are only accessible within the same object, meaning you cannot call them on other instances, even if they belong to the same class.
  2. Step 2: Compare with other visibility levels

    Protected methods allow access from other instances of the same class or subclasses, but private methods do not.
  3. Final Answer:

    It can only be called within the same object, not even by other instances of the same class. -> Option B
  4. Quick Check:

    Private = same object only [OK]
Hint: Private = only inside same object, no other instances [OK]
Common Mistakes:
  • Thinking private methods can be called on other instances
  • Confusing private with protected visibility
  • Assuming private methods are accessible outside the class
2. Which of the following is the correct syntax to declare a private method in a Ruby class?
easy
A. private def method_name end
B. private def method_name; end
C. def private method_name; end
D. def method_name; private; end

Solution

  1. Step 1: Recall Ruby private method syntax

    In Ruby, you declare private methods by writing private on its own line, then defining the method below it.
  2. Step 2: Check each option

    private on its own line followed by def method_name end is correct syntax. Putting private on the same line as def, prefixing def with private, or placing private inside the method are invalid.
  3. Final Answer:

    private def method_name end -> Option A
  4. Quick Check:

    private keyword on separate line before method [OK]
Hint: Use 'private' on its own line before method definition [OK]
Common Mistakes:
  • Trying to put 'private' inside method definition line
  • Using 'private def' which is invalid syntax
  • Placing 'private' after method definition
3. What will be the output of this Ruby code?
class Person
  protected
  def secret
    "protected info"
  end

  public
  def reveal_secret(other)
    other.secret
  end
end

p1 = Person.new
p2 = Person.new
puts p1.reveal_secret(p2)
medium
A. SyntaxError
B. NoMethodError: protected method `secret' called
C. protected info
D. nil

Solution

  1. Step 1: Understand protected method access

    Protected methods can be called by other instances of the same class. Here, p1 calls reveal_secret passing p2, and inside it calls other.secret.
  2. Step 2: Predict output

    Since secret is protected, p1 can call secret on p2. The method returns "protected info", which is printed.
  3. Final Answer:

    protected info -> Option C
  4. Quick Check:

    Protected allows calls between same class instances [OK]
Hint: Protected allows access between same class instances [OK]
Common Mistakes:
  • Thinking protected methods can't be called on other instances
  • Expecting NoMethodError for protected method call
  • Confusing protected with private access
4. Identify the error in this Ruby code:
class Animal
  private
  def sound
    "roar"
  end

  def make_sound(other)
    other.sound
  end
end

lion = Animal.new
tiger = Animal.new
puts lion.make_sound(tiger)
medium
A. NoMethodError: private method `sound' called for tiger
B. No error, outputs 'roar'
C. SyntaxError due to private method
D. ArgumentError in make_sound method

Solution

  1. Step 1: Understand private method restrictions

    Private methods cannot be called with an explicit receiver, even if the receiver is an instance of the same class.
  2. Step 2: Analyze the method call

    In make_sound, other.sound calls a private method on another instance, which is not allowed and raises NoMethodError.
  3. Final Answer:

    NoMethodError: private method `sound' called for tiger -> Option A
  4. Quick Check:

    Private methods can't be called on other instances [OK]
Hint: Private methods can't be called with explicit receiver [OK]
Common Mistakes:
  • Assuming private methods can be called on other instances
  • Confusing private and protected method rules
  • Expecting no error when calling private method on other object
5. You want to allow instances of a class to call a method on each other but keep it hidden from outside calls. Which visibility should you use and how would you implement it?
class User
  # Your code here
  def compare_password(other)
    self.password == other.password
  end

  private
  def password
    "secret123"
  end
end

u1 = User.new
u2 = User.new
puts u1.compare_password(u2)
hard
A. Use attr_accessor for password and keep it private.
B. Make password a private method; this code works as is.
C. Make password public; private and protected won't work.
D. Make password a protected method; private won't allow other.password call.

Solution

  1. Step 1: Understand method visibility for inter-instance calls

    Private methods cannot be called with an explicit receiver, so other.password will fail if password is private.
  2. Step 2: Use protected visibility

    Protected methods allow calls between instances of the same class, so changing password to protected allows other.password to work while keeping it hidden from outside.
  3. Final Answer:

    Make password a protected method; private won't allow other.password call. -> Option D
  4. Quick Check:

    Protected allows inter-instance calls, private does not [OK]
Hint: Use protected for inter-instance method access [OK]
Common Mistakes:
  • Keeping password private and expecting inter-instance calls to work
  • Making password public and exposing sensitive data
  • Using attr_accessor without protection
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard