Bird
0
0

Why does this Ruby code raise an error?

medium📝 Debug Q7 of 15
Ruby - Classes and Objects
Why does this Ruby code raise an error?
class User
  def initialize
    @name = name
  end
end
user = User.new("Alice")
AInstance variable @name cannot be assigned
Binitialize does not accept parameters but is called with one
CClass User is missing end keyword
DUser.new cannot be called without arguments
Step-by-Step Solution
Solution:
  1. Step 1: Check initialize method parameters

    The initialize method is defined without parameters but User.new is called with one argument.
  2. Step 2: Understand argument mismatch error

    This causes an argument error because the method does not expect any arguments.
  3. Final Answer:

    initialize does not accept parameters but is called with one -> Option B
  4. Quick Check:

    initialize parameters must match new arguments [OK]
Quick Trick: initialize parameters must match arguments passed to new [OK]
Common Mistakes:
  • Passing arguments to parameterless initialize
  • Confusing instance variable assignment
  • Missing class end keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes