【问题标题】:Ruby scopes: Diference between MyClass.new and ::MyClass.new [duplicate]Ruby 范围:MyClass.new 和 ::MyClass.new 之间的区别 [重复]
【发布时间】:2015-10-09 19:09:04
【问题描述】:

我知道双冒号 (::) 基本上是一个命名空间解析运算符。但在这种特殊情况下,我不确定我在哪个范围内工作。这是否意味着我想要来自 ruby​​ 核心的 MyClass 类?有点像 ~ 表示 bash 中的主目录..

【问题讨论】:

  • 正确!抱歉重复,但谢谢你的链接:)

标签: ruby scope


【解决方案1】:

想象一下下面的代码:

class A
  def a
    puts 'TOPMOST'
  end
end

module B
  class A
    def a
      puts 'NESTED'
    end
  end
  def self.topmost
    ::A.new.a
  end
  def self.nested
    A.new.a
  end
end

B.topmost 将打印"TOPMOST"B.nested 将打印"NESTED"

所以,::A 的意思不是“来自 ruby​​ 核心”,而是“来自没有模块”。

【讨论】:

  • 谢谢你的回答,真的很有帮助:)!
猜你喜欢
  • 1970-01-01
  • 2014-10-31
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
相关资源
最近更新 更多