ruby mixin 中奇怪的继承
我想知道,为什么包含的模块的方法会混合到任何后续的类定义中(就好像该类将其包含在自身中一样)?
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
prints:
There is no Bar.bar main Bar #<Bar:0xb73f2048>
这是预期的行为吗?为什么?
I am wondering, why is an included module's methods mixed in to any subsequent class definitions (as if the class included it in itself)?
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
prints:
There is no Bar.bar main Bar #<Bar:0xb73f2048>
Is this the expected behavior? Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您在程序中包含 Foo 但在任何类或方法之外时,它将包含在当前作用域中,即
main
对象。您可以通过将 bar 方法修改为以下内容来测试这一点
,然后在末尾添加以下 2 行
这将为您提供以下输出
When you include Foo in your program but outside of any class or method then it is included in to the current scope which is the
main
object.You could test this by modifying your bar method to the following
And then adding the following 2 lines at the end
This would give you the following output
顶层的
include
将模块混合到Object
中。只要它混合到Object
中,它就可以作为所有内容的实例方法。an
include
at top-level mixes the module intoObject
. In so far as it's mixed intoObject
it's available as an instance method on everything.