在Ruby上,为什么include是私有的而extend是公共的?
在 ruby 上,include
是私有的,而 Object#extend
是公共的,原因是什么?
On ruby, what is the reason for include
is private, while Object#extend
is public?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Object#extend
必须是公开的,否则你将无法使用它。毕竟,它的目的是将模块混合到对象中,因此您通常会像obj.extend(Foo)
那样调用它,这对于私有方法来说是不可能的。Module#include
通常仅在模块主体内部使用,如下所示:即,通常在没有接收器的情况下调用它,因此它不必是公共的。当然,它也不一定是私有的。
我的猜测是它是私有的原因是它更具侵入性,因为它改变了
Bar
的每个实例的行为,而Object#extend 仅更改单个对象。因此,
Module#include
在某种意义上“更危险”,因此被设为私有。我不知道这是否是真正的原因,但它与其他类似的方法(如
Module#define_method
)是一致的。Object#extend
has to be public, otherwise you wouldn't be able to use it. After all, its purpose is to mix in a module into an object, so you'd generally call it likeobj.extend(Foo)
, which isn't possible with private methods.Module#include
is usually only used inside a module body like so:I.e. it is usually called without a receiver, so it doesn't have to be public. Of course, it doesn't have to be private either.
My guess is the reason why it is private is that it is more invasive, because it changes the behavior of every instance of
Bar
, whereasObject#extend
only changes a single object. Therefore,Module#include
is in some sense "more dangerous" and thus is made private.I don't know whether that is the actual reason, but it is consistent with other similar methods like
Module#define_method
.能够在任何时候运行 Foo.include(Bar) 很可能会导致非常严重的错误。
To be able to run
Foo.include(Bar)
at any point would most likely be a source of very nasty bugs.为了补充 Jörg W Mittag 的答案,Object#extend 还可以用于包含要在类级别使用的模块实例方法(也可用于该类的所有实例):
To supplement Jörg W Mittag's answer, Object#extend can also be used to include module's instance methods to be used in the class level (which will also be available to all instances of that class):