在Ruby上,为什么include是私有的而extend是公共的?

发布于 2024-10-03 02:55:26 字数 84 浏览 5 评论 0原文

在 ruby​​ 上,include 是私有的,而 Object#extend 是公共的,原因是什么?

On ruby, what is the reason for include is private, while Object#extend is public?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

停滞 2024-10-10 02:55:26

Object#extend 必须是公开的,否则你将无法使用它。毕竟,它的目的是将模块混合到对象中,因此您通常会像 obj.extend(Foo) 那样调用它,这对于私有方法来说是不可能的。

Module#include 通常仅在模块主体内部使用,如下所示:

class Bar
  include Foo
end

即,通常在没有接收器的情况下调用它,因此它不必是公共的。当然,它也不一定是私有的。

我的猜测是它是私有的原因是它更具侵入性,因为它改变了 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 like obj.extend(Foo), which isn't possible with private methods.

Module#include is usually only used inside a module body like so:

class Bar
  include Foo
end

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, whereas Object#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.

隔岸观火 2024-10-10 02:55:26

能够在任何时候运行 Foo.include(Bar) 很可能会导致非常严重的错误。

To be able to run Foo.include(Bar) at any point would most likely be a source of very nasty bugs.

强辩 2024-10-10 02:55:26

为了补充 Jörg W Mittag 的答案,Object#extend 还可以用于包含要在类级别使用的模块实例方法(也可用于该类的所有实例):

module Foo
  def bar (baz)
  end
end

class Qux
  extend Foo

  bar 'asdf'
end

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):

module Foo
  def bar (baz)
  end
end

class Qux
  extend Foo

  bar 'asdf'
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文