Bird
0
0

Given this Ruby code, what is the output?

medium📝 Predict Output Q13 of 15
Ruby - Inheritance

Given this Ruby code, what is the output?

module M1
  def greet; "Hello from M1"; end
end

class C
  include M1
  def greet; "Hello from C"; end
end

obj = C.new
puts obj.greet
AHello from C
BHello from M1
CNoMethodError
DHello from Object
Step-by-Step Solution
Solution:
  1. Step 1: Understand method lookup order with include and override

    Class C includes module M1, but also defines its own greet method, which overrides the module's method.
  2. Step 2: Determine which greet method is called

    Ruby looks first in C, finds greet there, so it calls "Hello from C".
  3. Final Answer:

    Hello from C -> Option A
  4. Quick Check:

    Method override in class wins over included module [OK]
Quick Trick: Class methods override included module methods [OK]
Common Mistakes:
  • Thinking included module method runs first
  • Expecting NoMethodError due to confusion
  • Assuming Object's method is called

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes