class Point attr_accessor :x, :y def initialize(x, y) @x = x @y = y end end # 1 Module是不能實例化的 # 2 Module中既能夠有實例方法也能夠有類方法 module Helper def self.plus(obj) print obj.x + obj.y end def min(obj) print obj.x - obj.y end end p = Point.new(3, 4) # 3 模塊中的類方法直接經過模塊調用便可,而且類方法沒法被mixin Helper.plus(p) # 4 使用include將模塊的實例方法mix進來 當實例方法使用 # 5 使用extend將模塊的實例方法mix進來 當類方法使用 class Point include Helper extend Helper end Point.min(p) p.min(p) # 6 若是想同時mix 類方法和實例方法 module Helper2 # instance method def plus(obj) print obj.x + obj.y end # class method module ClassMethod def min(obj) print obj.x - obj.y end end # 只要當前這個module被include某個class中 這個方法就會被調用 # 將ClassMethod下的方法 mix成 類方法 def self.included(klass) klass.extend ClassMethod end end class Point2 attr_accessor :x, :y include Helper2 def initialize(x, y) @x, @y = x, y end end p = Point2.new(8, 4) Point2.min(p) p.plus(p) # 7 查看該類的模塊 p Point2.included_modules # 8 判斷是不是該模塊 p Point2.include?(Helper2) # 9 查看全部的祖先 其中包括模塊 p Point.ancestors # 10 去除其中的模塊部分 p Point.ancestors - Point.included_modules # 11 產看Point所屬類 所屬類爲Class Class也是類 p Point.class # 12 模塊屬於Module類 p Helper2.class # Class類的父類是模塊 全部Class的父類都是module p Point.class.superclass