- The main purpose of module is to put different methods and constants into different namespaces.
- The module is named in the same initial capitalization as the class, with multiple words without underlining. such as: Circlearea
- Module syntax
Module ModuleName
......
End
- The module uses the scope resolution operator "::" to invoke methods and constants in the module. For example:math::P i, math is the module name.
- Ways to import Modules:
1. Require ' module '-----import module.
Such as: Require ' date ', importing the date module, but not require ' date '
The module name and scope resolution operators are used when calling methods and constants in module, such as math::P I
2. Include module names, such as include Math
Calling methods and constants in a module does not require the Write module name and scope resolution operator to be called directly. such as: cos (), without the need to write Math::cos ()
- you can think of module as a class that cannot be instantiated, cannot be inherited, and can be emulated with classes to implement multiple inheritance
Module Martialarts
Def Swordsman
Puts "I ' m a swordsman."
End
End
Class Ninja
Include Martialarts
Def initialize (clan)
@clan = Clan
End
End
Class Samurai
Include Martialarts
Def initialize (shogun)
@shogun = Shogun
End
End
- The Include keyword lets an instance use the methods and constants in the model, and the Extend keyword allows the class to use the methods and constants in the model itself
Module Thepresent
def now
Puts "It ' s #{time.new.hour > 12? Time.new.hour-12:time.new.hour}:#{time.new.min} #{time.new.hour > 12? ' PM ': ' AM '} (GMT). "
End
End
Class Thehereand
Extend Thepresent
End
Thehereand.now
Ruby Module---modules, components