Bird
0
0

Identify the error in this Ruby class that tries to customize to_s:

medium📝 Debug Q14 of 15
Ruby - Classes and Objects
Identify the error in this Ruby class that tries to customize to_s:
class Car
  def initialize(model)
    @model = model
  end
  def to_s
    "Car model: " + model
  end
end

c = Car.new("Tesla")
puts c.to_s
AMissing return statement in to_s
BSyntax error in method definition
CUndefined local variable or method 'model'
DNo error, prints 'Car model: Tesla'
Step-by-Step Solution
Solution:
  1. Step 1: Check variable usage inside to_s

    The method uses model without @, but the instance variable is @model.
  2. Step 2: Understand Ruby variable scope

    Without @, Ruby looks for a local variable or method named model, which does not exist, causing an error.
  3. Final Answer:

    Undefined local variable or method 'model' -> Option C
  4. Quick Check:

    Instance variables need @ prefix inside methods [OK]
Quick Trick: Use @ before instance variables inside methods [OK]
Common Mistakes:
  • Forgetting @ before instance variables
  • Assuming local variables exist without definition
  • Thinking return statement is mandatory

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes