ruby中的模块详解

上一篇 / 下一篇  2012-11-02 20:12:16 / 个人分类:ruby

1、什么是模块
模块是方法与常量的集合。方法可以是实例方法或模块方法。实例方法如同引入模块的类的方法;相反,模块方法调用时不需要创建一个封装的对象。(译自官方api)
简单地说,类是模块的子类,类与模块具有一些相似的属性
2、创建和使用模块
1)创建模块
module First
#实例方法
 def mtd
  puts "method in module"
 end
#模块方法,调用时使用模块名.方法
 def First.mtd0
  puts "module method "
 end
end
2)类引用模块,一个类可以引用多个模块
module First
 def mtd
  puts "this is a module"
 end
end
class Test
  include First
end
Test.new.mtd
输出结果:
this is a module
3、模块与类嵌套,调用时使用模块名::类名.new
module Second
  class Test2
    def method
      puts "module include class"
    end
  end
end
test = Second::Test2.new
test.method
输出结果:
module include class

TAG: module Ruby ruby

 

评分:0

我来说两句

Open Toolbar