include defined in Module and therefore can only be called on modules and classes (which are modules). It adds constants, (instances) of methods, and (modular) variables from the given module (s) to the receiver, calling append_features .
extend , on the other hand, is defined in Object , that is, it is not limited to modules and classes. It adds instance methods from the given module (s) to the receiver or, more precisely, to the monophonic receiver class.
Here's an example module with the hello instance method:
module Mod def hello "Hello from #{self.class} '#{self}'" end end
If we extend instance (as opposed to a class), then hello becomes an instance method:
str = 'abc' str.extend(Mod) str.hello #=> "Hello from String 'abc'"
If we extend the class, then hello will become a class method:
String.extend(Mod) String.hello #=> "Hello from Class 'String'"
This is because class methods are really just instance methods defined in a singleton class of the class.
However, there are several options for defining class and instance methods by calling extend and / or include :
1. extend and include
This is the easiest, you can move the include Name from Person to Joe :
module Person include Arms, Legs end class Joe extend Person include Name end
2. extend and include in the superclass
Or you can make a Person class that extend and include other modules, and use it as a Joe superclass:
class Person extend Arms, Legs include Name end class Joe < Person end
The following options include some Ruby magic โ they use a callback to call include after extend or vice versa:
3. include from extended
You can use the extended include Name callback from Person :
module Person include Arms, Legs def self.extended(mod) mod.include(Name) end end class Joe extend Person end
4. extend from included
Or you could include Person from Joe and use the included callback to call extend :
module Person include Name def self.included(mod) mod.extend Arms, Legs end end class Joe include Person end
3 and 4 look clean within Joe , but it may not be obvious (maybe confusing?) That including or extending Person also defines class or instance methods.