Using "::" instead of "module ..." for Ruby namespacing
In Ruby, is there a difference between writing class Foo::开发者_开发技巧Bar
and module Foo; class Bar
for namespacing? If so, what?
If you use class Foo::Bar
, but the Foo
module hasn't been defined yet, an exception will be raised, whereas the module Foo; class Bar
method will define Foo
if it hasn't been defined yet.
Also, with the block format, you could define multiple classes within:
module Foo
class Bar; end
class Baz; end
end
Also notice this curious bit of 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
精彩评论