在看别人的源码是,发现这样一句 path = ::File.expand_path 双冒号后面的我能理解,唯独是为什么双冒号前面可以不用加任何东西?? 求各位帮忙解答下!谢谢!
这个类似 /代表根目录的意思吧。如果不写的话,可能会引用到某个 Module 内的 File 吧。
好像是强制使用外包的 File 类来着(不确定有没有搞反),这类情况一般是自己的项目也有个类叫 File,为了区别内部的和外部的
明白了~谢谢大家~
楼主好头像....
有个 Ruby 教程 Koans Test 里提过这个用法
require "test/unit" class AboutScope < Test::Unit::TestCase # --------- class String end def test_bare_bones_class_names_assume_the_current_scope assert_equal true, AboutScope::String == String end def test_nested_string_is_not_the_same_as_the_system_string assert_equal false, String == "HI".class end def test_use_the_prefix_scope_operator_to_force_the_global_scope assert_equal true, ::String == "HI".class end # --------- PI = 3.1416 def test_constants_are_defined_with_an_initial_uppercase_letter assert_equal AboutScope::PI, PI end # --------- MyString = ::String def test_class_names_are_just_constants assert_equal true, MyString == ::String assert_equal true, MyString == "HI".class end def test_constants_can_be_looked_up_explicitly assert_equal true, PI == AboutScope.const_get("PI") assert_equal true, MyString == AboutScope.const_get("MyString") end end
::是命名空间的分隔符啊 前面不加东西 则代表顶层的命名空间咯
谢谢各位的回答,明白啦!哈哈
记得 C++ 好像是全局函数的意思~,ruby 的就是跟模块命名空间~jasl 大神说的对~