Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Modules and Mixins
What will be the output of this Ruby code?
module Talkative
  def speak
    "Hello!"
  end
end

class Person
  include Talkative
end

p = Person.new
puts p.speak
AHello!
BNoMethodError
Cnil
DSyntaxError
Step-by-Step Solution
Solution:
  1. Step 1: Understand module inclusion

    The module Talkative defines a method speak. The class Person includes this module, so instances of Person get the speak method.
  2. Step 2: Check method call and output

    Creating a new Person instance and calling p.speak will return "Hello!" which is printed by puts.
  3. Final Answer:

    Hello! -> Option A
  4. Quick Check:

    Included module methods are available to instances = B [OK]
Quick Trick: Included module methods become instance methods [OK]
Common Mistakes:
  • Expecting NoMethodError because of missing inheritance
  • Confusing extend with include
  • Thinking module methods are class methods by default

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes