0
0
Rubyprogramming~5 mins

Namespacing with modules in Ruby

Choose your learning style9 modes available
Introduction

Modules help keep your code organized by grouping related things together. They also prevent name clashes when different parts of your program use the same names.

When you want to group related methods or constants together.
When you want to avoid conflicts between method or class names in large programs.
When you want to create a clear structure for your code, like folders for files.
When you want to share methods across different classes without inheritance.
When you want to create a namespace to separate similar names.
Syntax
Ruby
module ModuleName
  # code here
end
Use module keyword followed by the module name starting with a capital letter.
You can nest modules inside each other for deeper organization.
Examples
This module has a method that can be called with Greetings.say_hello.
Ruby
module Greetings
  def self.say_hello
    puts "Hello!"
  end
end
This shows a nested module Birds inside Animals to organize related code.
Ruby
module Animals
  module Birds
    def self.info
      puts "Birds can fly."
    end
  end
end
The class Hammer is inside the Tools module to avoid name clashes with other Hammer classes.
Ruby
module Tools
  class Hammer
    def hit
      puts "Bang!"
    end
  end
end
Sample Program

This program defines a Toaster class inside nested modules Kitchen and Appliances. We create a new toaster and call its toast method.

Ruby
module Kitchen
  module Appliances
    class Toaster
      def toast
        puts "Toasting bread!"
      end
    end
  end
end

toaster = Kitchen::Appliances::Toaster.new

toaster.toast
OutputSuccess
Important Notes

Use :: to access classes or modules inside modules.

Modules cannot be instantiated like classes; they are containers for code.

Modules can also be used to mix in methods to classes using include or extend.

Summary

Modules group related code and prevent name conflicts.

Use nested modules for better organization.

Access nested code with the :: operator.