Consider the following Ruby code that uses include to add instance methods from a module to a class. What will be printed when the code runs?
module Greetings def hello "Hello from module!" end end class Person include Greetings end p = Person.new puts p.hello
Remember that include adds module methods as instance methods to the class.
The include Greetings line adds the hello method from the Greetings module as an instance method to the Person class. So calling p.hello prints "Hello from module!".
Look at this Ruby code where a module method is called on an instance of a class that does not include the module. What will happen?
module Talk def speak "Speaking" end end class Animal end a = Animal.new puts a.speak
Think about whether the class has access to the module's methods without including it.
The Animal class does not include the Talk module, so instances of Animal do not have the speak method. Calling a.speak raises a NoMethodError.
Examine the Ruby code below. It tries to include a module for instance methods, but raises an error. What is the cause?
module Friendly def greet "Hi!" end end class Robot include Friendly() end r = Robot.new puts r.greet
Look closely at the include Friendly() statement.
The include Friendly() line causes Ruby to evaluate Friendly() as the argument to include. Modules do not define a () method, so it raises NoMethodError: undefined method `()' for Friendly:Module. The correct syntax is include Friendly.
In Ruby, when a module is included in a class, how does it affect the method lookup path for instance methods?
Think about how Ruby searches for methods when you call them on an instance.
Including a module inserts it into the class's ancestor chain just above the class. This means the module's instance methods are found before the class's own methods during method lookup.
Analyze the following Ruby code where a class includes two modules with methods of the same name. What will be printed?
module A def info "Module A" end end module B def info "Module B" end end class MyClass include A include B def info "MyClass" end end obj = MyClass.new puts obj.info
Remember that methods defined in the class override included module methods.
The method info defined in MyClass overrides the methods from modules A and B. So calling obj.info prints "MyClass".