2010-07-24 79 views
2

我在想,为什么被包含的模块的方法混入到任何后续的类定义中(就好像类中包含了它自己一样)?在ruby mixins中的奇怪继承

module Foo 
    def bar 
    print "#{self}\n" 
    end 
end 

class Bar 
end 

begin 
    Bar.bar 
rescue NoMethodError 
    puts "There is no Bar.bar\n" 
end 

include Foo 

bar 
Bar.bar 
Bar.new.bar

打印:

 
There is no Bar.bar 
main 
Bar 
#<Bar:0xb73f2048> 

这是预期的行为?为什么?

+0

你期待什么? – 2010-07-24 17:38:34

回答

2

如果在程序中包含Foo但不包含任何类或方法,那么它将包含在当前作用域中,即main对象。

你可以通过修改你的杆法以下

def bar 
    print "InBar class: #{self.class} value: #{self}\n" 
    end 

,然后在年底

2.bar 
Fixnum.bar 

添加以下两行这会给你下面的输出

测试这个
There is no Bar.bar 
InBar class: Object value: main 
InBar class: Class value: Bar 
InBar class: Bar value: #<Bar:0x21ecec> 
InBar class: Fixnum value: 2 
InBar class: Class value: Fixnum 
+0

'main'实际上不是一个类,它是一个对象。因为“包括”不应该(严格)在顶层提供。尽管如此,'include'可以作为一种特殊情况(便利方法)使用,但其行为是将该模块混合到“Object” – horseyguy 2010-07-24 23:49:45

+0

@banister中。谢谢手指比脑子快。适当编辑 – 2010-07-25 05:34:50

2

an include在顶层混合模块为Object。就其被混合到Object而言,它在所有方面都可用作实例方法。