对Ruby命名空间使用“::”而不是“module …”
在Ruby中,编写class Foo::Bar
和module Foo; class Bar
之间有区别module Foo; class Bar
module Foo; class Bar
? 如果是这样,什么?
如果使用class Foo::Bar
,但尚未定义Foo
模块,则会引发exception,而module Foo; class Bar
如果还没有定义,则module Foo; class Bar
方法将定义Foo
。
此外,使用块格式,您可以在以下内容中定义多个类:
module Foo class Bar; end class Baz; end end
还要注意这个奇怪的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