Ruby - Module Modules Basics

Introduction

Modules solve name conflicts by providing namespaces that can contain any number of classes, methods, and constants.

For example:

Demo

module NumberStuff 
  def NumberStuff.random 
    rand(1000000) #   w w w  . j  a  v  a2  s.  c om
  end 
end 

module LetterStuff 
  def LetterStuff.random 
    (rand(26) + 65).chr 
  end 
end 

puts NumberStuff.random 
puts LetterStuff.random

Result

Here it's clear which version of random you're trying to use in the two last lines.

The modules defined in the preceding code look a little like classes.

Modules provide ways to organize methods, classes, and constants into separate namespaces.

Related Topics