Bird
0
0

Given this code, what will puts D.greet output?

hard📝 Application Q9 of 15
Ruby - Advanced Metaprogramming

Given this code, what will puts D.greet output?

module M
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def greet
      "Hi from M"
    end
  end
end

module N
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def greet
      "Hi from N"
    end
  end
end

class D
  include M
  include N
end

puts D.greet
AHi from N
BHi from M
CNoMethodError
DSyntaxError
Step-by-Step Solution
Solution:
  1. Step 1: Understand module inclusion order

    Modules included later override earlier ones. Here, N is included after M.
  2. Step 2: Identify which greet method is used

    Since N is included last, its greet method overrides M's method.
  3. Final Answer:

    Hi from N -> Option A
  4. Quick Check:

    Last included module methods override earlier ones [OK]
Quick Trick: Last included module methods override previous ones [OK]
Common Mistakes:
  • Assuming first included module wins
  • Expecting NoMethodError
  • Confusing extend with include order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes