新建一个trig.rb程序并写入:
#-*-coding:UTF-8 -*-
#Ruby模块Module
# 模块提供了一个命名空间和避免名字冲突。模块实现了 mixin 装置。
module Trig
PI=3.14
def Trig.sin(x)
puts "sinx"
end
def Trig.cos(x)
puts "cosx"
end
end
再新建一个moral.rb程序并写入:
</pre><pre class="ruby" name="code">#-*-coding:UTF-8 -*-
#Ruby模块Module
# 模块提供了一个命名空间和避免名字冲突。模块实现了 mixin 装置。
module Moral
VERY_BAD=0
BAD=1
def Moral.sin(badness)
puts "sinx"
end
end
然后在主程序中调用以上两个程序文件:
# require 语句类似于 C 和 C++ 中的 include 语句以及 Java 中的 import 语句。如果一个第三方的程序想要使用任何已定义的模块,则可以简单地使用 Ruby require 语句来加载模块文件:
# 在这里,文件扩展名 .rb 不是必需的
$LOAD_PATH <<'.'
# 使用 $LOAD_PATH << '.' 让 Ruby 知道必须在当前目录中搜索被引用的文件。
# 如果您不想使用 $LOAD_PATH,那么您可以使用 require_relative 来从一个相对目录引用文件。
require 'trig.rb'
require 'moral.rb'
y=Trig.sin(Trig::PI/4)
wrongdoing=Moral.sin(Moral::VERY_BAD)
二、在类中引用如下:
新建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
再在主程序中的类中引用如下:
# 您可以在类中嵌入模块。为了在类中嵌入模块,您可以在类中使用 include 语句:
$LOAD_PATH << '.'
require "support" #可以不用加.rb
# 您可以在类中嵌入模块。为了在类中嵌入模块,您可以在类中使用 include 语句:
$LOAD_PATH << '.'
require "support" #可以不用加.rb
class Decade
include Week #引用其中的模块
no_of_yrs=10
def no_of_months
puts Week::FIRST_DAY
number=12*10
puts number
end
end
d1=Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month #引入模块就把模块内的函数和字段当成自己的
Week.weeks_in_year
d1.no_of_months
三、Mixins代表了多重基础,Mixins不是关键字
# Ruby 中的 Mixins
# 当一个类可以从多个父类继承类的特性时,该类显示为多重继承。
# Ruby 不直接支持多重继承,但是 Ruby 的模块(Module)有另一个神奇的功能。它几乎消除了多重继承的需要,提供了一种名为 mixin 的装置。
module A
def a1
puts "sucess a1"
end
def a2
puts "sucess a2"
end
end
module B
def b1
puts "sucess b1"
end
def b2
puts "sucess b2"
end
end
class Sample
include A
include B
def s1
puts "sucess s1"
end
end
samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1