ruby 中的 module
2014-02-14 17:08
344 查看
Module是Class的父类:
>> Class.superclass
=> Module
module 没有实例变量
module 没有new不能生成实例对象
module内可以有常量
module的方法有两种,一种是module方法,这类方法可以直接调用。
另一种是没有module名字的方法,这种方法不能直接调用,需要mixin到一个类中。
把module的方法添加到类中有两种方法。
一种是include,方法会被添加到实例方法中。
一种是extend,方法会被添加到类方法中。
继续前面的module Test的例子
module常用的一个hook/callback是included方法,这个方法在module被include到一个类中的时候会被调用。
>> Class.superclass
=> Module
module 没有实例变量
module 没有new不能生成实例对象
module内可以有常量
>> module Test >> PI=3.14 >> end => 3.14 >> Test.PI >> Test::PI => 3.14
module的方法有两种,一种是module方法,这类方法可以直接调用。
>> module Test >> def Test.test_method >> puts "hello from module" >> end >> end => nil >> Test::test_method hello from module => nil
另一种是没有module名字的方法,这种方法不能直接调用,需要mixin到一个类中。
>> module Test >> def hello >> puts "hello" >> end >> end => nil >> Test::hello NoMethodError: undefined method `hello' for Test:Module from (irb):23
把module的方法添加到类中有两种方法。
一种是include,方法会被添加到实例方法中。
一种是extend,方法会被添加到类方法中。
继续前面的module Test的例子
>> class Class1 >> include Test >> end => Class1 >> Class1.new.hello hello => nil >> class Class2 >> extend Test >> end => Class2 >> Class2.hello hello => nil
module常用的一个hook/callback是included方法,这个方法在module被include到一个类中的时候会被调用。
>> module Test >> def self.included(cls) >> puts "including module in class #{cls.name}" >> end >> end => nil >> class Class1 >> include Test >> end including module in class Class1 => Class1
相关文章推荐
- YAML简介及应用(c/c++ 和 ruby)
- ruby中的Proc类的理解
- ruby中对字符串的操作
- 一个ruby工程师的2013年个人工作总结
- 在ubuntu下的ruby文件不能运行
- Ruby. Vs . Python
- Ruby on Rails 入门 ----respond_to
- Ruby+Watir测试环境搭建
- ruby命令
- Ruby China中method_missing和define_method剖析
- ruby 之super和super()的区别
- 广州云宏信息科技有限公司诚聘ruby工程师
- cloud foundry dea源码解析
- RubyMine的快捷键总结
- ruby中form 提交数组对象
- Ruby 的循环的使用
- 【ruby】安装Ruby
- ruby判断数字类型函数
- 增强的XML?通过C# 4.0 dynamic享受Ruby写法之探讨
- ruby之三元运算符写法