Bird
0
0

What will this Ruby code print? class Cat def initialize(name) @name = name end def name @name end end cat = Cat.new("Whiskers") puts cat.name

medium📝 Predict Output Q5 of 15
Ruby - Classes and Objects
What will this Ruby code print? class Cat def initialize(name) @name = name end def name @name end end cat = Cat.new("Whiskers") puts cat.name
Anil
B@name
CError: undefined method
DWhiskers
Step-by-Step Solution
Solution:
  1. Step 1: Initialize instance variable @name

    The constructor sets @name to "Whiskers".
  2. Step 2: The name method returns @name

    Calling cat.name returns the value of @name, which is "Whiskers".
  3. Final Answer:

    Whiskers -> Option D
  4. Quick Check:

    Instance variable access returns stored value [OK]
Quick Trick: Instance variables keep data accessible across methods [OK]
Common Mistakes:
  • Expecting @name to print literally
  • Not defining a method to access @name
  • Confusing local variables with instance variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes