Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Advanced Metaprogramming

What will be the output of this Ruby code?

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

  module ClassMethods
    def greet
      "Hello!"
    end
  end
end

class C
  include M
end

puts C.greet
Anil
BNoMethodError
CSyntaxError
DHello!
Step-by-Step Solution
Solution:
  1. Step 1: Understand the included hook behavior

    The included hook extends the including class C with the ClassMethods module, adding its methods as class methods.
  2. Step 2: Identify the method call

    Calling C.greet works because greet is added as a class method by the extension.
  3. Final Answer:

    Hello! -> Option D
  4. Quick Check:

    Included hook extends class with methods = Hello! [OK]
Quick Trick: included hook can add class methods via extend [OK]
Common Mistakes:
  • Expecting greet as instance method
  • Not realizing extend adds class methods
  • Confusing included with prepend

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes