0
0
Rubyprogramming~5 mins

Module declaration syntax in Ruby

Choose your learning style9 modes available
Introduction

Modules help group related methods and constants together. They keep code organized and avoid repeating code.

When you want to group helper methods used in many places.
When you want to share code between classes without inheritance.
When you want to create namespaces to avoid name conflicts.
When you want to add reusable behavior to classes using mixins.
Syntax
Ruby
module ModuleName
  # code here
end

Module names start with a capital letter and use CamelCase.

Use end to close the module block.

Examples
This defines a module named Greetings with a method hello.
Ruby
module Greetings
  def hello
    puts "Hello!"
  end
end
This module holds a constant PI that can be used elsewhere.
Ruby
module MathHelpers
  PI = 3.14
end
Modules can be nested to create namespaces.
Ruby
module Outer
  module Inner
    def self.info
      puts "Inside Inner module"
    end
  end
end
Sample Program

This program defines a module Tools with a method greet that returns a greeting message. We call it and print the result.

Ruby
module Tools
  def self.greet(name)
    "Hello, #{name}!"
  end
end

puts Tools.greet("Alice")
OutputSuccess
Important Notes

You cannot create instances of modules like classes.

Modules are often used with include or extend to add methods to classes.

Summary

Modules group related code and constants.

Use module Name ... end to declare a module.

Modules help organize code and share behavior without inheritance.