ruby简单的基本 6
2015-07-02 21:47
465 查看
模
像类似的模块,那里 class method 和 instance method。module 没有new不能生成对象的例子
其中 class method 所谓的模块在模块化的方法,它能够直接调用。
module Foo def self.hello puts 'hello world!' end def Foo.dear #module全局作用域内的self还是没有变,就是Module; puts 'dear..' end NUM = 100 end
Foo.hello #=> 'hello world!' 调用模块方法 模块名字.方法名字
Foo.dear #=> 'dear..' 调用模块方法 模块名字.方法名字
Foo::NUM #=> 100 引用一个常数,使用模块名和两个冒号。
而对于模块里面的 instance method 实例方法,这样的方法不能直接调用。须要mixin到一个类中。
主要有两种形式:
一种是include,方法会被加入到实例方法中。
一种是extend,方法会被加入到类方法中。
module M def self.m_fun puts 'm fun' end def instance_fun puts 'instance fun' end NUM = 100 end M.m_fun M::m_fun puts M::NUM puts '-----------------' class A include M end #A.m_fun #A.instance_fun #A.new.m_fun A.new.instance_fun puts '-----------------' class B extend M end #B.m_fun B.instance_fun #B.new.m_fun #B.new.instance_fun
一些总结
require, load,include都是Kernel模块中的方法。他们的差别例如以下:require,load用于包括文件。include则用于包括的模块。
require载入一次,load可载入多次。
require载入Ruby代码文件时能够不加后缀名,load载入代码文件时必须加后缀名。
require用于加载普通情况下的库文件。和load用于加载配置文件。
相关文章推荐
- 如何以非 root 用户将应用绑定到 80 端口-ssh 篇 » 社区 » Ruby China
- 使用 Capistrano 和写作 Ruby 迭代边缘部署
- 在ruby 2 和rails 4 里面使用send_file 下载文件的时候。在IE下面中文名出现乱码的处理方式
- ruby的入门基础
- ubuntu安装Ruby on rails
- CocoaPods
- ubuntu 14.04中安装ruby on rails环境(填坑版)
- Ruby Profiler 详解之 ruby-prof(I)
- Ruby高手点评Scala编程语言十大绝招
- Ruby on Rails Tutorial 第一章 之 Heroku部署
- Ruby on Rails Tutorial 第一章 之 Git项目管理
- Ruby on Rails Tutorial 第一章 之 搭建开发环境
- Ruby on Rails Tutorial 第一章 之 简介
- RUBY-超大数字操作
- RUBY-类、对象练习
- RUBY-hash操作
- RUBY-数组操作
- RUBY-二进制文件操作
- RUBY-文件、目录操作
- RUBY-字符串操作