ruby简单的基本 6

像类似的模块,那里 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用于加载配置文件。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/mfrbuaa/p/4617220.html