Bird
0
0

What is the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Modules and Mixins
What is the output of this Ruby code?
module M
  def greet
    "Hello from M, " + super
  end
end

class C
  prepend M
  def greet
    "Hello from C"
  end
end

puts C.new.greet
A"Hello from C"
B"Hello from M, Hello from C"
CNoMethodError
D"Hello from M"
Step-by-Step Solution
Solution:
  1. Step 1: Understand method lookup with prepend

    Because M is prepended, its greet method is called first.
  2. Step 2: Follow the super call in module method

    The super inside M#greet calls the original greet in C, returning "Hello from C".
  3. Step 3: Combine returned strings

    The module method returns "Hello from M, " + "Hello from C" resulting in "Hello from M, Hello from C".
  4. Final Answer:

    "Hello from M, Hello from C" -> Option B
  5. Quick Check:

    Prepend + super calls original method [OK]
Quick Trick: Prepend runs module method first; super calls original method [OK]
Common Mistakes:
  • Ignoring super call and expecting only module output
  • Thinking prepend replaces original method without super
  • Expecting NoMethodError due to super

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes