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用于加载配置文件。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值