Ruby的include和extend


在ruby中基本上有三种引入module的方式 
一、在类定义中引入module后,module中的方法成为类的实例方法。 
在类定义中用include引入module。 
例如: 
Ruby代码 
module Base 
def test 
p "This is a instance method!" 
end 
end 

class Car 
include Base 
end 
Car.new.test => "This is a instance method!" 

module Base
def test
p "This is a instance method!"
end
end

class Car
include Base
end
Car.new.test => "This is a instance method!"

二、在类定义中引入module后,module中的方法成为类的类方法。 
在类定义中用extend引入module。 
例如: 
Ruby代码  
module Base 
def test 
p "This is a instance method!" 
end 
end 

class Car 
extend Base 
end 
Car.test => "This is a class method!" 

module Base
def test
p "This is a instance method!" 
end
end

class Car
extend Base
end
Car.test => "This is a class method!"

三、在类定义中引入module后,module中的方法即有成为类的实例方法,又有成为类的类方法。 
这需要在类定义中引入module时,用include。 
例如: 
Ruby代码  
module Base 
def test 
p "This is a instance method!" 
end 
def self.included(base) 
def base.call 
p "This is a class method---call" 
end 
base.extend(ClassMethods) 
end 
module ClassMethods 
def hello 
p "This is a class method----hello" 
end 
end 
end 

class Car 
include Base 
end 

Car.new.test => "This is a instance method!" 
Car.call => "This is a class method---call" 
Car.hello => "This is a class method---hello" 

module Base
def test
p "This is a instance method!"
end
def self.included(base)
def base.call
p "This is a class method---call"
end
base.extend(ClassMethods)
end
module ClassMethods
def hello
p "This is a class method----hello"
end
end
end

class Car
include Base
end

Car.new.test => "This is a instance method!"
Car.call => "This is a class method---call"
Car.hello => "This is a class method---hello"

参考资料: 
1、http://developer.51cto.com/art/200907/132919.htm 
2、http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/ 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值