1、module 模块不能被实例化,也不能被子类化。模块是独立的,在继承体系中没有任何所谓的“模块等级”。所有的类都是模块,但并非所有的模块都是类。
模块名需用大写字母开头。定义一个模块会创建一个跟模块同名的常量,这个常量的值是一个Module对象,用于代表那个模块。
module Base64 #constant DIGITS = "ABCDEF" # Method def self.encode end def self.decode end end #This is how we invoke the methods of the Base64 module test = Base64.encode(data) data = Base64.decode(text) str = Base64::DIGITS
2、模块用于混入想把一个模块混入一个类中,使用include
class Point include Comparable end
3、可以把一个模块包含在另一个模块中module Iterable include Enumerable def each loop {yield self.next} end en
4、使用Object.extend方法,使模块实例方法成为接收对象的单键方法。countdown = Object.new #The each iterator as a singleton Method def countdown.each yield 1 yield 2 yield 3 end countdown.extend(Enumerable) print countdown.sort #=> [1,2,3]