Consider this Ruby module and class. What will be printed when MyClass.new.greet is called?
module Greeter def self.included(base) puts "Greeter included in #{base}" end def greet "Hello!" end end class MyClass include Greeter end puts MyClass.new.greet
Remember that self.included runs when the module is included in a class.
The included hook runs when the module is included, printing the message with the class name. Then greet returns "Hello!" which is printed by puts.
What will be the output of this Ruby code?
module Tracker def self.included(base) base.class_eval do def tracked_method "Tracked method called" end end end end class Widget include Tracker end puts Widget.new.tracked_method
The included hook can add methods to the including class dynamically.
The included hook uses class_eval to add tracked_method to the class, so calling it works and prints the string.
Given these modules and class, what is printed when Example.new.test is called?
module A def self.included(base) puts "Module A included" end def test "A" end end module B def self.included(base) puts "Module B included" end def test "B" end end class Example include A include B end puts Example.new.test
Modules included later override methods of earlier modules.
Both included hooks run in order of inclusion, printing their messages. The last included module B overrides test, so calling test returns "B".
What error will this Ruby code raise?
module M def self.included(base) base.undefined_method end end class C include M end
Calling a method that does not exist on a class raises a NoMethodError.
The included hook tries to call undefined_method on the class C, which does not exist, causing a NoMethodError.
Which statement best describes the difference between include with an included hook and extend in Ruby modules?
Think about what methods are added and when the included hook runs.
include adds instance methods to a class and triggers the included hook. extend adds methods as class methods and does not trigger included.