gpt4 book ai didi

Ruby 的双冒号(::)操作符使用差异

转载 作者:数据小太阳 更新时间:2023-10-29 06:26:52 26 4
gpt4 key购买 nike

有什么区别吗

module Foo
class Engine < Rails::Engine
end
end

module Foo
class Engine < ::Rails::Engine
end
end

最佳答案

Ruby 中的常量就像文件系统中的文件和目录一样嵌套。因此,常量由它们的路径唯一标识。

用文件系统打个比方:

::Rails::Engine #is an absolute path to the constant.
# like /Rails/Engine in FS.

Rails::Engine #is a path relative to the current tree level.
# like ./Rails/Engine in FS.

这里是可能的错误的说明:

module Foo

# We may not know about this in real big apps
module Rails
class Engine
end
end

class Engine1 < Rails::Engine
end

class Engine2 < ::Rails::Engine
end
end

Foo::Engine1.superclass
=> Foo::Rails::Engine # not what we want

Foo::Engine2.superclass
=> Rails::Engine # correct

关于Ruby 的双冒号(::)操作符使用差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10482772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com