无涯教程-Ruby - 模块语句

88 阅读2分钟

Module 语法

module Identifier
   statement1
   statement2
   ...........
end

模块常量的命名与类常量一样,并带有大写字母开头。方法定义也看起来相似:模块方法的定义就像类方法一样。

与类方法一样,您可以通过在模块名称前加上模块名称和句点来调用模块方法,并使用模块名称和两个冒号::来引用常量。

#!/usr/bin/ruby

# Module defined in trig.rb file

module Trig PI=3.141592654 def Trig.sin(x) # .. end def Trig.cos(x) # .. end end

无涯教程可以再定义一个具有相同函数名称但函数不同的模块-

#!/usr/bin/ruby

# Module defined in moral.rb file

module Moral VERY_BAD=0 BAD=1 def Moral.sin(badness) # ... end end

与类方法一样,每当在模块中定义方法时,都需要指定模块名称,后跟一个点,然后指定方法名称。

Require 语句

Require语句类似于C和C++的include语句以及Java的import语句。如果第三个程序想要使用任何已定义的模块,则可以使用Ruby require 语句简单地加载模块文件-

require filename

在这里,不需要给出 .rb 扩展名以及文件名。

$LOAD_PATH << .

require trig.rb require moral

y=Trig.sin(Trig::PI/4) wrongdoing=Moral.sin(Moral::VERY_BAD)

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

Mixin混合

Ruby不直接支持多重继承,但是Ruby Modules还有另一个很好的用法。它提供了名为 mixin 的函数,几乎消除了对多重继承的问题。

Mixins为您提供了一种极好的受控方式,可以为类添加函数。但是,当mixin中的代码开始与使用它的类中的代码进行交互时,它们的真正力量才显现出来。

让无涯教程检查以下示例代码以了解mixin-

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

模块A由方法a1和a2组成。模块B由方法b1和b2组成。 Sample类包括模块A和B。Sample类可以访问所有四个方法,即a1,a2,b1和b2。因此,您可以看到类Sample继承自两个模块。因此,您可以说Sample类显示了多重继承或 mixin

参考链接

www.learnfk.com/ruby/ruby-m…