0
0
Rubyprogramming~10 mins

Protected and private visibility in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the method private.

Ruby
class Person
  def initialize(name)
    @name = name
  end

  [1] def secret
    "My name is #{@name}"
  end
end
Drag options to blanks, or click blank then click option'
Amodule
Bprotected
Cprivate
Dpublic
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'protected' instead of 'private' makes the method accessible to subclasses.
2fill in blank
medium

Complete the code to make the method accessible to instances of the same class and subclasses.

Ruby
class Person
  def initialize(name)
    @name = name
  end

  [1] def greet(other)
    "Hello, #{other.name}!"
  end

  attr_reader :name
end
Drag options to blanks, or click blank then click option'
Aprotected
Bpublic
Cprivate
Dmodule
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'private' prevents calling the method on other instances.
3fill in blank
hard

Fix the error in the code by choosing the correct visibility keyword for the method.

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

  [1] def display_balance
    "Balance: $#{@balance}"
  end
end

account = BankAccount.new(1000)
puts account.display_balance
Drag options to blanks, or click blank then click option'
Aprivate
Bprotected
Cmodule
Dpublic
Attempts:
3 left
💡 Hint
Common Mistakes
Marking the method private or protected causes a NoMethodError when called externally.
4fill in blank
hard

Fill both blanks to define a protected method and call it from another instance of the same class.

Ruby
class User
  def initialize(name)
    @name = name
  end

  [1] def secret_message(other)
    "Secret for #{other.name}"
  end

  def reveal_secret(other)
    other.[2](self)
  end

  attr_reader :name
end
Drag options to blanks, or click blank then click option'
Aprotected
Bprivate
Csecret_message
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Using private keyword prevents calling the method on other instances.
5fill in blank
hard

Fill both blanks to define a private method and call it correctly inside the class.

Ruby
class SecretAgent
  def initialize(code_name)
    @code_name = code_name
  end

  def reveal
    [1]
  end

  [2] def code
    "Agent: #{@code_name}"
  end
end
Drag options to blanks, or click blank then click option'
Acode
Bprivate
Cself.code
Dpublic
Attempts:
3 left
💡 Hint
Common Mistakes
Calling private method with 'self.' causes an error.