Ruby的include和extend

本文介绍了Ruby中三种引入Module的方法:使用include使Module的方法成为类的实例方法;使用extend使Module的方法成为类方法;同时使用include和extend则Module中的方法既作为实例方法也作为类方法存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在ruby中基本上有三种引入module的方式
一、在类定义中引入module后,module中的方法成为类的实例方法。
在类定义中用include引入module。
例如:
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。
例如:
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。
例如:
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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值