Ruby 教程 之 Ruby 模块(Module) 3
Ruby 模块(Module)
Ruby include 语句
您可以在类中嵌入模块。为了在类中嵌入模块,您可以在类中使用 include 语句:
语法
include modulename
如果模块是定义在一个单独的文件中,那么在嵌入模块之前就需要使用 require 语句引用该文件。
实例
假设下面的模块写在 support.rb 文件中。
module Week
FIRST_DAY = "Sunday"
def Week.weeks_in_month
puts "You have four weeks in a month"
end
def Week.weeks_in_year
puts "You have 52 weeks in a year"
end
end
现在,您可以在类中引用该模块,如下所示:
实例
!/usr/bin/ruby
$LOAD_PATH << '.'
require "support"
class Decade
include Week
no_of_yrs=10
def no_of_months
puts Week::FIRST_DAY
number=10*12
puts number
end
end
d1=Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year
d1.no_of_months
这将产生以下结果:
Sunday
You have four weeks in a month
You have 52 weeks in a year
Sunday
120