- An
Object
is a set of instance variables and a pointer to a 'singleton class'. - Properties are looked up in the instance variables, methods are dispatched via the singleton class.
Module
is a subtype ofObject
. AModule
is a set of methods and an ordered list of zero-or-more 'parent' modules.- Module
A
becomes a parent of moduleB
viaB.include(A)
. - Method lookup works by doing a depth-first right-to-left search of a module tree.
Class
is a subtype ofModule
. AClass
is aModule
that can be instantiated.- A
Class
has only one 'superclass'. A class includes its superclass as its first parent module for the purposes of method dispatch. A class's singleton class includes the superclass's singleton class as its first parent. - The default superclass of all classes is
Object
. Object
includes theKernel
module as a parent.
- Although
Class
is a subtype ofModule
, you cannot callB.include(A)
ifA
is aClass
. - Singleton classes are not really classes. You cannot instantiate or inherit from them.
obj.extend(M)
is sugar forobj.singleton_class.include(M)
.
@r4vi: I think you're conflating two things. One is opening the singleton class of an object:
which also works on classes (and modules), since they're a kind of object too. Inside a class definition,
self
is the class being defined, so:which is the same as
Unrelated, you can also mix a module into the module's metaclass. That sounds complicated, but it means that the module's methods (which are instance methods) become available on the module object itself. Thus:
You can also do this upfront like so:
There happens to be another way to achieve the same end, which for some reason is called
module_function
: