欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ruby的include和extend

程序员文章站 2022-07-16 08:58:55
...


在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代码 Ruby的include和extend
            
    
    博客分类: ruby   Ruby的include和extend
            
    
    博客分类: ruby  Ruby的include和extend
            
    
    博客分类: 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代码 Ruby的include和extend
            
    
    博客分类: ruby   Ruby的include和extend
            
    
    博客分类: ruby  Ruby的include和extend
            
    
    博客分类: 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/