您的位置:首页 > 编程语言 > Ruby

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用于加载配置文件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: