Ruby Module 的基础概念

定义一个 Mudule

Module Flyable
def fly
puts "I can fly"
end
end

或者这样

module Mod
  include Math       # 引用别的 module
  CONST = 1         
  def meth
    #  ...
  end
end
Mod.class              #=> Module
Mod.constants          #=> [:CONST, :PI, :E]
Mod.instance_methods   #=> [:meth]

引用 Module

Class Dog
include Flyable
end

cut_dog = Dog.new
cut_dog.fly       

# =>  "I can fly"

建立模块函数

module HelloModule
    Version = '1.0'         # 定义常量
    
    def hello(name)         # 定义方法
        puts "Hello, #{name}."
    end
    
    module_function :hello  # 指定 hello 方法为模块函数, 为模块私有
    
end

p HelloModule::Version  #=> "1.0"
HelloModule.hello("San")    #=> Hello, San.

include HelloModule     # 包含模块
p Version               #=> "1.0"
hello("Jiang")          #=> Hello, Jiang.

注意:

  1. 没有new不能生成实例对象
  2. 模块不能被继承
  3. 没有实例对象,自然没有实例变量 (不存在 @xyz )
  4. Module内可以有常量
  5. 可以内置别的 Module

在线文档链接:

Class: Module (Ruby 2.5.3)