Ruby Modules

christian.dinh's avatar
Published Jul 29, 2021Updated Sep 9, 2021

In Ruby, modules are collections of classes, methods, and constants. They lend extra functionality to classes that include them.

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours

Syntax

Modules are defined with a module...end block. For example:

module ModuleName
include OtherModule
CONSTANT = 123
def method_1
...
end
def method_2
...
end
end

Usage in a Class

module TwoTermSolver
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
def multiply (a, b)
a * b
end
def divide(a, b)
begin
a / b
rescue ZeroDivisionError
puts "Division by zero (0) is not allowed."
end
end
end
class Calculator
include TwoTermSolver
end
puts Calculator.new.add(3, 4) # Output: 7

All contributors

Learn Ruby on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours