ruby救援不断失踪?

发布于 2024-11-30 08:40:54 字数 246 浏览 1 评论 0原文

几个月前,我一直在使用一些 ruby​​ 库(不幸的是,我不记得到底是哪一个),

我很惊讶地发现它允许我用类似的东西初始化它的实例:

Lib::SOMETHING(args)

我真的不明白它是如何实现的可能会起作用。我非常确定它应该是动态的(没有任何常量),例如constant_missing模块方法,或者可能以某种方式处理ConstantMissing异常。

您能给建议吗?

few months ago I've been using some ruby library ( I can't recall which one exactly, unfortunately )

I've been surprised to see it allowed me to initialize it's instance with something like that:

Lib::SOMETHING(args)

I don't really understand how it could possibly work. I'm pretty much sure it should be something dynamic ( there's no SOMETHING constant ) like constant_missing module method or maybe the ConstantMissing exception gets handled somehow.

Could you please advice?

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

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

发布评论

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

评论(1

伏妖词 2024-12-07 08:40:54

理论上没有什么神奇之处,它只是看起来不熟悉:

class A
  def self.I_LOOK_LIKE_A_CONST(arg)
    puts arg
  end
end

A::I_LOOK_LIKE_A_CONST("Hi") # => "Hi"

Net::HTTP 与其 Proxy 类做了类似的事情,它允许诸如 Net::HTTP 之类的调用: :Proxy(...),它的定义类似:

def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil)

要点是,对于类方法,您可以互换使用 ::. 来调用它们。

No magic there in theory, it just looks unfamiliar:

class A
  def self.I_LOOK_LIKE_A_CONST(arg)
    puts arg
  end
end

A::I_LOOK_LIKE_A_CONST("Hi") # => "Hi"

Net::HTTP does something similar with its Proxy class, it allows calls such as Net::HTTP::Proxy(...), it is defined similarly:

def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil)

The punch line is that for class methods you can interchangeably use :: or . to invoke them.

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