模块
module.rb
=begin 1、模块(Module)是一种把方法、类和常量组合在一起的方式。 2、模块(Module)为您提供了两大好处: *模块提供了一个命名空间和避免名字冲突。 *模块实现了 mixin 装置。 3、模块类似与类,但有以下不同: *模块不能实例化 *模块没有子类 *模块只能被另一个模块定义 =end $LOAD_PATH << '.' #在当前目录中搜索被引用的文件 require 'support' puts Module1::A #使用模块名称+两个冒号来引用一个常量 Module1.test #类方法名称前面放置模块名称和一个点号来调用模块方法 puts "....................." #在类中引用模块 class Module include Week #include后面直接跟模块名 def test1 puts "methods in class" end end puts Week::FIRST_DAY m = Module.new m.test1 Week.weeks_in_month #直接使用模块名+方法名 Week.weeks_in_year puts "......................" #通过模块使用mixin,即消除多重继承 module A def a1 puts "a1" end def a2 puts "a2" end end module B def b1 puts "b1" end def b2 puts "b2" end end class Sample include A include B def s puts "s" end end samp = Sample.new samp.s samp.a1 samp.a2 samp.b1 samp.b2
support.rb
module Module1 A = 22 def Module1.test #注意该方法的命名规则 puts "this is Module1" end end module Week FIRST_DAY = "sunday" def Week.weeks_in_month #当在模块中定义方法时,可以是模块名+方法名 puts "4 weeks in a month" end def weeks_in_year #当在模块中定义方法时,直接方法名貌似也可以 puts "52 weeks in a year" end end =begin 总结: 当模块直接被另外一个文件使用时,模块内的方法必须命名为:模块名.方法名 当模块被另外一个文件的类应用时,模块内的方法可以命名为:方法名 =end