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

Ddl1st · 2013年01月10日 · 最后由 springirl 回复于 2016年09月01日 · 22508 次阅读
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 屠龙之技 (恢复) 提及了此话题。 06月21日 14:08
需要 登录 后方可回复, 如果你还没有账号请 注册新账号