Modules
Anonymous contributor
Published Jul 29, 2021Updated Sep 9, 2021
Contribute to Docs
In Ruby, modules are collections of classes, methods, and constants. They lend extra functionality to classes that include them.
Syntax
Modules are defined with a module...end
block. For example:
module ModuleNameinclude OtherModuleCONSTANT = 123def method_1...enddef method_2...endend
Usage in a Class
module TwoTermSolverdef add(a, b)a + benddef subtract(a, b)a - benddef multiply (a, b)a * benddef divide(a, b)begina / brescue ZeroDivisionErrorputs "Division by zero (0) is not allowed."endendendclass Calculatorinclude TwoTermSolverendputs Calculator.new.add(3, 4) # Output: 7
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Ruby on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn Ruby
Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.Beginner Friendly9 hours