ruby 模块

来源:互联网 发布:新手网球拍淘宝 编辑:程序博客网 时间:2024/04/29 09:47


1、module  模块不能被实例化,也不能被子类化。模块是独立的,在继承体系中没有任何所谓的“模块等级”。所有的类都是模块,但并非所有的模块都是类。

模块名需用大写字母开头。定义一个模块会创建一个跟模块同名的常量,这个常量的值是一个Module对象,用于代表那个模块。

[ruby] view plaincopy
  1. <pre name="code" class="ruby">module Base64  
  2.     #constant  
  3.     DIGITS = "ABCDEF"  
  4.       
  5.     # Method   
  6.     def self.encode  
  7.     end  
  8.       
  9.     def self.decode  
  10.     end  
  11. end  
  12.   
  13.   
  14. #This is how we invoke the methods of the Base64 module  
  15. test = Base64.encode(data)  
  16. data = Base64.decode(text)  
  17. str = Base64::DIGITS</pre><br>  
  18. <br>  
  19. <p></p>  
  20. <pre></pre>  
  21. <br>  
  22. 2、模块用于混入  
  23. <p></p>  
  24. <p>想把一个模块混入一个类中,使用include</p>  
  25. <p></p><pre name="code" class="ruby">class Point  
  26.     include Comparable  
  27. end</pre><br>  
  28. 3、可以把一个模块包含在另一个模块中<p></p>  
  29. <p></p><pre name="code" class="ruby">module Iterable  
  30.     include Enumerable  
  31.     def each  
  32.         loop {yield self.next}  
  33.     end  
  34. en</pre><br>  
  35. 4、使用Object.extend方法,使模块实例方法成为接收对象的单键方法。<p></p>  
  36. <p></p><pre name="code" class="ruby">countdown = Object.new  
  37. #The each iterator as a singleton  Method  
  38. def countdown.each  
  39.     yield 1  
  40.     yield 2  
  41.     yield 3  
  42. end  
  43.   
  44. countdown.extend(Enumerable)  
  45.   
  46. print countdown.sort   #=> [1,2,3]</pre><br>  
  47. <br>  
  48. <p></p>  
  49. <br> 
0 0
原创粉丝点击