Module Basics
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: