Module Basics
A module is a named container for related methods and values, like a toolbox with a label. It is not something you make objects from, but something to share.
In this page:
Syntax
module ModuleName
CONSTANT = value
def self.method_name
# body
end
end
ModuleName.method_name
Module Basics
A module is defined with module ModuleName ... end, grouping related methods, constants, and classes together, similar to a class but without the ability to be instantiated with .new.
Modules serve two main purposes: namespacing (organizing related code) and mixins (sharing behavior across classes). They're a core part of how Ruby avoids needing multiple class inheritance.
Note:
Trying to call SomeModule.new raises a NoMethodError -- modules cannot be instantiated directly, unlike classes.
Example: Module Basics
module MathHelpers
def self.square(n)
n * n
end
end
puts MathHelpers.square(6)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Defining
def squarewithoutself.and callingMathHelpers.square, which raisesNoMethodError. - Naming a module in lowercase such as module math_helpers, which is a syntax error because module names must be constants starting with a capital letter.
- Trying
MathHelpers.new, which raisesNoMethodErrorbecause a module cannot be instantiated.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: