模組是 Ruby 實現命名空間隔離與程式碼複用(Mixin)的核心機制。本文說明模組定義、require/include、常數存取、以及 Mixin 如何替代多重繼承。
module Trig
PI = 3.141592654
def Trig.sin(x); ... end
def Trig.cos(x); ... end
end
module Moral
VERY_BAD = 0
def Moral.sin(badness); ... end
end
呼叫模組方法:Trig.sin(Trig::PI/4)
存取常數:Trig::PI
require 'trig'
require 'moral'
y = Trig.sin(Trig::PI/4)
模組避免同名方法衝突,需以模組名限定呼叫。
# support.rb
module Week
FIRST_DAY = "Sunday"
def Week.weeks_in_month; puts "一月四週"; end
def Week.weeks_in_year; puts "一年52週"; end
end
# 主程式
require "support"
class Decade
include Week
def no_of_months
puts Week::FIRST_DAY
puts 10 * 12
end
end
d1 = Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year
d1.no_of_months
Ruby 不支援多重繼承,但可 include 多個模組:
module A; def a1; end; def a2; end; end
module B; def b1; end; def b2; end; end
class Sample
include A
include B
def s1; end
end
samp = Sample.new
samp.a1; samp.a2; samp.b1; samp.b2; samp.s1 # 全部可呼叫
Sample 同時擁有 A、B 的方法,實現「多重繼承」效果。