Bird
0
0

Find the error in this Ruby class:

medium📝 Debug Q6 of 15
Ruby - Classes and Objects
Find the error in this Ruby class:
class Animal
  def initialize(name)
    name = name
  end
  def get_name
    @name
  end
end
pet = Animal.new("Buddy")
puts pet.get_name
AThe class name should be lowercase
BThe instance variable @name is not assigned in initialize
Cget_name method should be private
DThe initialize method is missing
Step-by-Step Solution
Solution:
  1. Step 1: Check variable assignment in initialize

    The code assigns name = name, which only assigns the parameter to itself, not to an instance variable.
  2. Step 2: Understand instance variable usage

    The get_name method returns @name, but @name was never set, so it will be nil.
  3. Final Answer:

    The instance variable @name is not assigned in initialize -> Option B
  4. Quick Check:

    initialize must assign @name = name to store value [OK]
Quick Trick: Use @ to assign instance variables inside initialize [OK]
Common Mistakes:
  • Assigning parameter to itself
  • Forgetting @ for instance vars
  • Thinking method privacy causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes