ruby 的module 与类

来源:互联网 发布:淘宝卖qq号码是真的吗 编辑:程序博客网 时间:2024/05/17 09:09

ruby 的module 与类

    博客分类: 
  • java
 
ruby模块与类 

Class类是Module的子类,类是一种特殊形式的模块, Class, Module, Object,Kernel的关系。 

我们知道最顶级的类是Object,那么最顶级的模块就是Kernel 

我们使用模块的的主要目的是用来组织代码,模块化代码,有点类似命名空间,但却有很大的不同。 

一、创建和使用模块 

用module关键字来定义模块 

module FirstModule 
     def  say 
         puts "hello" 
     end 
end 


module没有实例,我们使用时把module混合到类中来使用,我们也可以这么理解,把Module里的内容拷贝一份放到类里,成为类的一部分。 

module FirstModule 
     def  say 
         puts "hello" 
     end 
end 
class ModuleTest 
      include FirstModule 
end 

test=ModuleTest.new 
test.say 
#hello 

我们可以把模块放到一个单独的文件里,然后使用时进行加载,看下面的示例,假设我们有一个project.rb的文件,包含了Project模块 

module Project 
    attr_accessor  :member 
     def initialize 
         @member=Array.new 
     end 
     def add(name) 
         member.push(name) 
     end 
    
     def del 
         member.pop 
     end 
end 

require "project" 

class Manager 
include Project 
end 

manager=Manager.new 

manager.add("tom"); 
manager.add("lili"); 
#tom 


注意: 在使用require或load时,请求加载的内容放到引号里,而inclue不是用引号,这是因为require或load使用字符串做为参数,而include使用常量形式的模块名,require和load使用字符串变量也可以. 

二、混合进模块的类的方法查找 

module  A 
   def say 
         puts "hello" 
   end 
end 

class B 
include A 
end 

class C <B 
end 

test =C.new 

test.say 
上面say方法查找路径为 C类-->C类里包含的模块-->B类-->B类包含的模块......>Object-->Kernel,当找到第一个时,搜索停止。 

同名方法的查找,后面覆盖前面的. 


module A 
     def say 
          puts "hello from A" 
     end 
end 

module B 
    def say 
          puts "hello from B" 
    end 
end 

class C 
    include A 
    include B 
end 

test =C.new 
test.say 

#output: hello from B 

super提升查找路径(调用查找路径上下一个匹配的方法),同样我们使用super可以调用父类的同名方法,initialize是自动执行 


module A 
     def say 
         puts "hello from A" 
     end 
end 

class B 
    include A 
     def say 
          puts "in say from B" 
          super 
          puts "out say from B" 
     end 
end 

test =B.new 
test.say 

# in say from B 
#hello from A 
#out say from B 

三、模块和类可以相互嵌套 

module也可以包含类,但调用时需要这样使用 模块名::类名.new 

module   A 
     class B 
          def say 
               puts "hello" 
          end 
     end 
end 

test =A::B.new 
test.say
原创粉丝点击