在Ruby中,写入class Foo::Bar和module Foo; class Bar命名空间之间有区别吗?如果是这样,什么?
如果使用class Foo::Bar,但Foo尚未定义模块,则会引发异常,而该module Foo; class Bar方法将定义Foo是否尚未定义.
此外,使用块格式,您可以在以下内容中定义多个类:
module Foo
class Bar; end
class Baz; end
end
Run Code Online (Sandbox Code Playgroud)
还要注意这个奇怪的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)