Challenge - 5 Problems
Ruby Visibility Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of calling a private method from outside the class
What will be the output of this Ruby code?
Ruby
class Person private def secret "my secret" end end p = Person.new puts p.secret
Attempts:
2 left
💡 Hint
Private methods cannot be called with an explicit receiver.
✗ Incorrect
In Ruby, private methods cannot be called with an explicit receiver, even if that receiver is self. Calling p.secret raises NoMethodError.
❓ Predict Output
intermediate2:00remaining
Output of calling a protected method from another instance
What will this Ruby code print?
Ruby
class Person def initialize(name) @name = name end protected def secret "secret of #{@name}" end public def reveal_secret(other) other.secret end end p1 = Person.new("Alice") p2 = Person.new("Bob") puts p1.reveal_secret(p2)
Attempts:
2 left
💡 Hint
Protected methods can be called by instances of the same class.
✗ Incorrect
Protected methods can be called by any instance of the defining class or its subclasses. p1 calls p2.secret successfully.
🔧 Debug
advanced2:00remaining
Why does this code raise an error?
This Ruby code raises an error. What is the cause?
Ruby
class BankAccount private def balance 1000 end public def show_balance balance end end account = BankAccount.new puts account.balance
Attempts:
2 left
💡 Hint
Check where the private method is called from.
✗ Incorrect
Calling account.balance from outside the class is not allowed because balance is private and called with an explicit receiver.
❓ Predict Output
advanced2:00remaining
Output when calling protected method from subclass instance
What will this Ruby code print?
Ruby
class Animal protected def sound "generic sound" end end class Dog < Animal def make_sound(other) other.sound end end d1 = Dog.new d2 = Dog.new puts d1.make_sound(d2)
Attempts:
2 left
💡 Hint
Protected methods are accessible within subclasses and instances of the same class.
✗ Incorrect
Protected methods can be called by instances of the same class or subclasses. d1 calls d2.sound successfully.
📝 Syntax
expert2:00remaining
Identify the syntax error related to method visibility
Which option contains a syntax error in defining method visibility in Ruby?
Attempts:
2 left
💡 Hint
Check how private is used to declare methods.
✗ Incorrect
Option A is invalid syntax because 'private secret' is not a valid way to declare method visibility. It should be 'private :secret'.