1

有时我会看到这样的代码:

module Elite

    module App
        def app
            'run app'
        end
    end

    module Base
        def base
            'base module'
        end
    end

    class Application
        include Elite::Base #Include variant A
        include ::Elite::App #Include variant B

        def initialize(str=nil) 
            puts "Initialized with #{str}"
            puts "Is respond to base?: #{base if self.respond_to?(:base)}"
            puts "Is respond to app?: #{app if self.respond_to?(:app)}"

        end
    end

    class Store < ::Elite::Application

        def initialize(str=nil)
            super #Goes to Application init
        end
    end
end

elite = Elite::Store.new(:hello)

但我不明白class Store < ::Elite::Applicationandclass Store < Elite::Applicationinclude Elite::Baseand之间有什么不同include ::Elite::App 只是编码风格,还是有什么不同?

类/模块之前做什么::?:: 类/模块的干净命名空间(模块名称)?因为class Store < Application有效,但这不起作用:class Store < ::Application. 请告诉我有什么区别...谢谢!

4

1 回答 1

3

'::' 是基本(全局)范围运算符。

所以'::Application'引用了基础应用程序,而'Application'引用了当前范围内的应用程序。

例如

class Application # Class 1
end

class Smile
  class Application # Class 2
  end

  ::Application # references class 1
  Application # references class 2 (The application in my current scope)
end
于 2012-05-10T20:28:24.510 回答