Bird
0
0

Find the error in this Ruby class declaration:

medium📝 Debug Q7 of 15
Ruby - Classes and Objects
Find the error in this Ruby class declaration:
class Person
  def initialize(name)
    @name = name
  end

  def name
    @name
  end

  def name=(value)
    @name = value
  end

end

p = Person.new("Alice")
p.name = 123
puts p.name
AError: cannot assign integer to name
BNo error, code runs and prints 123
CMissing 'end' for class
DCannot use '@name' instance variable
Step-by-Step Solution
Solution:
  1. Step 1: Review class and methods

    The class defines an initializer, a getter, and a setter for @name. Ruby allows any type for instance variables.
  2. Step 2: Check code execution

    Creating a Person with "Alice", then setting p.name = 123 changes @name to 123. Printing p.name outputs 123.
  3. Final Answer:

    No error, code runs and prints 123 -> Option B
  4. Quick Check:

    Ruby instance variables accept any value type [OK]
Quick Trick: Ruby instance variables can hold any data type [OK]
Common Mistakes:
  • Expecting type errors
  • Missing 'end' keywords
  • Misusing instance variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes