对Ruby命名空间使用"::"而不是"module ..."

myb*_*ael 10 ruby namespaces

在Ruby中,写入class Foo::Barmodule Foo; class Bar命名空间之间有区别吗?如果是这样,什么?

Dyl*_*kow 9

如果使用class Foo::Bar,但Foo尚未定义模块,则会引发异常,而该module Foo; class Bar方法将定义Foo是否尚未定义.

此外,使用块格式,您可以在以下内容中定义多个类:

module Foo
  class Bar; end
  class Baz; end
end
Run Code Online (Sandbox Code Playgroud)

  • 此外,如果`Foo`被定义为一个类`Foo :: Bar`将不会引发`module Foo; end`将引发一个`TypeError`,因为`Foo`不是一个模块而是一个类. (2认同)

Cas*_*per 7

还要注意这个奇怪的Ruby-ismness:

FOO = 123

module Foo
  FOO = 555
end

module Foo
  class Bar
    def baz
      puts FOO
    end
  end
end

class Foo::Bar
  def glorf
    puts FOO
  end
end

puts Foo::Bar.new.baz    # -> 555
puts Foo::Bar.new.glorf  # -> 123
Run Code Online (Sandbox Code Playgroud)

  • 很酷,如果你想关注,这是我发布的新SO问题:http://stackoverflow.com/questions/15119724/ruby-lexical-scope-vs-inheritance (2认同)