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
  attr_writer :age
  def initialize(age)
    @age = age
  end
  def show_age
    @age
  end
end

p = Person.new(30)
puts p.show_age
p.age = 40
puts p.show_age
A30\n40
B30\n30
CError: undefined method `age='
DError: undefined method `show_age'
Step-by-Step Solution
Solution:
  1. Step 1: Understand attr_writer effect

    attr_writer :age creates a setter method age=, but no getter method is created.
  2. Step 2: Analyze method calls

    p.show_age returns @age which is 30 initially. Then p.age = 40 sets @age to 40. But p.show_age returns @age which is now 40.
  3. Step 3: Check output

    Actually, p.show_age is called twice, before and after setting age. So outputs are 30 then 40.
  4. Final Answer:

    30\n40 -> Option A
  5. Quick Check:

    attr_writer allows setting, show_age reads @age [OK]
Quick Trick: attr_writer only sets; custom getter needed [OK]
Common Mistakes:
  • Assuming attr_writer creates getter method
  • Expecting error on p.age= assignment
  • Confusing show_age method with attr_reader

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes