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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With