Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Classes and Objects
What will be the output of this Ruby code?
class Person
  def initialize(name)
    @name = name
  end
  def to_s
    "Person named #{@name}"
  end
end

p = Person.new("Alice")
puts p.to_s
A#<Person:0x00007fffe>
BError: undefined method to_s
CAlice
DPerson named Alice
Step-by-Step Solution
Solution:
  1. Step 1: Understand the custom to_s method

    The class Person defines to_s to return "Person named #{@name}", where @name is set to "Alice".
  2. Step 2: Check what puts p.to_s prints

    Calling p.to_s returns "Person named Alice", which is printed by puts.
  3. Final Answer:

    Person named Alice -> Option D
  4. Quick Check:

    Custom to_s returns formatted string [OK]
Quick Trick: Custom to_s returns your string, not default object info [OK]
Common Mistakes:
  • Expecting default object id string instead of custom string
  • Confusing instance variable with method name
  • Thinking to_s is undefined

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes