Bird
0
0

Given this Ruby code, what will be the output?

hard📝 Application Q15 of 15
Ruby - Inheritance
Given this Ruby code, what will be the output?
class A
  def message
    "A"
  end
end

class B < A
  def message
    "B" + super
  end
end

class C < B
  def message
    super + "C"
  end
end

puts C.new.message
A"ABC"
B"BCA"
C"BAC"
D"CAB"
Step-by-Step Solution
Solution:
  1. Step 1: Trace method calls from C to A

    C#message calls super which is B#message. B#message returns "B" + super which calls A#message returning "A".
  2. Step 2: Combine returned strings step-by-step

    B#message returns "B" + "A" = "BA". Then C#message returns "BA" + "C" = "BAC".
  3. Final Answer:

    "BAC" -> Option C
  4. Quick Check:

    super chains add strings in order [OK]
Quick Trick: super calls chain up; combine results in call order [OK]
Common Mistakes:
  • Mixing order of concatenation
  • Assuming super calls only immediate parent
  • Ignoring that super returns parent's result

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes