Ruby Ruby 中 双冒号"::" 的功能

Ddl1st · January 10, 2013 · Last by springirl replied at September 01, 2016 · 22507 hits
module Foo

  class Bar; end

  class ::FooBar
     def self.method1
       "method1"
     end
  end
end
Foo::Bar
FooBar
FooBar::method1
=> "method1"

那一般的方法用 . 来调用只是个人喜好或约定?

#1 楼 @blacktulip 可能你没看明白问题把。 问题的例子中已经列出了所有的功能,其实类名也是一个常量 我问的是 "个人喜好或约定?"

class Foo
  def bar ; end
end

Foo::new::bar

没什么硬性约定,一般为了保持一致性,call method 统一用 . ,让人一看就知道是 method call

综上所述 如果 Foo::小写 (new,test)---->就去需找方法 如果 Foo::大写 (A,VERSION)--->就去寻找常量

#1 楼 @blacktulip 你好!下面的 ::File 就是表示回到 root namespace 的意思么?

def existing_git_clone?
  ::File.exist?(::File.join(@new_resource.destination, ".git"))
end

def target_dir_non_existent_or_empty?
  !::File.exist?(@new_resource.destination) || Dir.entries(@new_resource.destination).sort == ['.','..']
end

完整的代码在 这里

已经在 这里 找到答案,希望没有打扰到你,不好意思!

# coding: utf-8
class Mao
  PPP='aaaaa'
  def ppp
    puts "maohaofu"
  end

end
def maomao
  puts ::Mao.new::ppp
  puts ::Mao:: new::ppp # 和上一行一样效果
  puts ::Mao::PPP
end
maomao()

这样会不会明白些

输出

maohaofu

maohaofu

aaaaa

luikore in 屠龙之技 (恢复) mention this topic. 21 Jun 14:08
You need to Sign in before reply, if you don't have an account, please Sign up first.