在 Ruby 中,如何为从“ENV”等常量获取的对象设置别名?

发布于 2025-01-12 05:53:06 字数 276 浏览 5 评论 0原文

鉴于 ENV 既不是类也不是模块,因此不可能使用以下常用机制直接为其单例方法之一添加别名:

class SomeClass
  class << self
    alias some_alias some_existing_method
  end
end

是否有一种方法可以为类似 ENV 的方法添加别名::[]?

Given that ENV is neither a class nor a module, it is not possible to directly alias one of its singleton methods with the following usual mechanism:

class SomeClass
  class << self
    alias some_alias some_existing_method
  end
end

Is there nonetheless a way to alias a method like ENV::[]?

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

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

发布评论

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

评论(1

无语# 2025-01-19 05:53:06

是的,这是可能的,技巧是在单例类的上下文中评估别名语句:

  ENV.singleton_class.class_eval do
      alias jet []
  end

Yes, it's possible, the trick is to evaluate the alias statement within the context of the singleton class:

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