Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Inheritance
What will be the output of this Ruby code?
module Mixin
  def greet
    'Hello from Mixin'
  end
end

class Parent
  def greet
    'Hello from Parent'
  end
end

class Child < Parent
  include Mixin
end

puts Child.new.greet
AHello from Mixin
BHello from Parent
CNoMethodError
DSyntaxError
Step-by-Step Solution
Solution:
  1. Step 1: Understand method lookup with modules

    Including a module in a class inserts the module above the class in the method lookup chain.
  2. Step 2: Determine which greet method is called

    Child includes Mixin, so greet from Mixin overrides Parent's greet.
  3. Final Answer:

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

    Module method overrides parent method = Hello from Mixin [OK]
Quick Trick: Included modules override parent class methods [OK]
Common Mistakes:
  • Assuming parent method always overrides module methods
  • Confusing include with inheritance
  • Expecting NoMethodError when method exists in module

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes