1、module 模块不能被实例化,也不能被子类化。模块是独立的,在继承体系中没有任何所谓的“模块等级”。所有的类都是模块,但并非所有的模块都是类。
模块名需用大写字母开头。定义一个模块会创建一个跟模块同名的常量,这个常量的值是一个Module对象,用于代表那个模块。
- <pre name="code" class="ruby">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</pre><br>
- <br>
- <p></p>
- <pre></pre>
- <br>
- 2、模块用于混入
- <p></p>
- <p>想把一个模块混入一个类中,使用include</p>
- <p></p><pre name="code" class="ruby">class Point
- include Comparable
- end</pre><br>
- 3、可以把一个模块包含在另一个模块中<p></p>
- <p></p><pre name="code" class="ruby">module Iterable
- include Enumerable
- def each
- loop {yield self.next}
- end
- en</pre><br>
- 4、使用Object.extend方法,使模块实例方法成为接收对象的单键方法。<p></p>
- <p></p><pre name="code" class="ruby">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]</pre><br>
- <br>
- <p></p>
- <br>