We can think that module is a toolbox dedicated to storing a series of methods and constants.
The module and class are very similar, but the module cannot create an instance or have sub-classes. They can only store things.
For example:
module Circle PI = 3.141592653589793 def Circle.area(radius) PI * radius**2 end def Circle.circumference(radius) 2 * PI * radius endend
Module writing format
module ModuleName #end
Just like a class name, the module name also uses uppercase letters without the underscore _.
One of the main functions of the module is to separate methods and constants into a namespace, which is called namespacing. This will not confuse Math :: pi and circle: Pi are two different PI values. Two colons: called the range resolution operator, which is used to tell Ruby where to find the value or method we need. If we want to find Math: PI, ruby knows to go to the math module to find pi.
Some modules are already included in the Ruby interpreter, but some need to be explicitly included. We can use the keyword require, as shown below:
require "module"
If we want to use Ruby's date module to display today's date, but we haven't included it with require, we need to perform the following operations:
require "date"puts Date.today
Of course we can use require to include more modules, but we can also use the include keyword.
If any class includes a module, this class can use this module method.
One advantage of using include is that we no longer have to write the module name containing constants or methods, because all information in the module has been included in the class of the include module, we can directly use PI instead of Math: PI, as shown below:
class Angle include Math attr_accessor :radians def initialize(radians) @radians = radians end def cosine cos(@radians) endendacute = Angle.new(1)acute.cosine
Ruby Learning Module