0
0
Rubyprogramming~20 mins

Protected and private visibility in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Visibility Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
Anil
Bmy secret
CNoMethodError
DSyntaxError
Attempts:
2 left
💡 Hint
Private methods cannot be called with an explicit receiver.
Predict Output
intermediate
2: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)
Anil
BNoMethodError
Csecret of Alice
Dsecret of Bob
Attempts:
2 left
💡 Hint
Protected methods can be called by instances of the same class.
🔧 Debug
advanced
2: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
Abalance is private and cannot be called with an explicit receiver outside the class
Bbalance method is not defined
Cshow_balance method is private
DSyntax error in class definition
Attempts:
2 left
💡 Hint
Check where the private method is called from.
Predict Output
advanced
2: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)
ANoMethodError
Bgeneric sound
Cnil
DArgumentError
Attempts:
2 left
💡 Hint
Protected methods are accessible within subclasses and instances of the same class.
📝 Syntax
expert
2:00remaining
Identify the syntax error related to method visibility
Which option contains a syntax error in defining method visibility in Ruby?
A
class Test
  def secret
    42
  end
  private secret
end
B
class Test
  def secret
    42
  end
  private :secret
end
C
class Test
  private
  def secret
    42
  end
end
D
class Test
  private def secret
    42
  end
end
Attempts:
2 left
💡 Hint
Check how private is used to declare methods.