A module in Ruby is not
as it is in Python. It is an object with
and attributes defined within a
block of code, like a class, but without the ability to be
module MyModule # Module
are constants (capitalized) MyConst = "Module Constant MyModule::MyConst" $my_global = "Unrelated to module namespace (global is global)" my_local = "Inaccessible from without" module NestedModule # Access via MyModule::NestedModule end class InnerClass end def module_method # Can be accessed as MyModule.module_method end module_function :module_method end module AnotherModule # In same file... end
You can define more than one module in the same source file, and even nest them inside each other to organize your namespace. Loading an external file with module definitions is the same as defining them in the source file, and there is no requirement to give these external files the same
as your module(s).
Once defined in the source file, a module is immediately available. You can access nested modules or constants via the
scope operator, and module functions (shared public methods) via dot notation. You may also as a whole include the module into a class namespace, or extend any object with its methods. There is no provision for selectively including constants or methods of a module as Python's
allows, because it is
to be a single unit.
When you use this
such shared code from multiple sources, the included modules become part of the single inheritance tree, similar to a subclass. Yes, order does matter.
class MyString < String end p MyString.ancestors # [ MyString, String, ...] module AlterString end class MyString include AlterString end p MyString.
# [ MyString, AlterString, String, ...]
module is not
but referenced, as in Python.