10

In Ruby, is there a difference between writing class Foo::Bar and module Foo; class Bar for namespacing? If so, what?

mybuddymichael
  • 1,660
  • 16
  • 20

2 Answers2

9

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
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • 2
    Also if `Foo` was defined as a class `Foo::Bar` won't raise the exception while `module Foo; end` will raise a `TypeError` since `Foo` is not a module but a class. – Roberto Decurnex Aug 03 '11 at 14:53
7

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
Casper
  • 33,403
  • 4
  • 84
  • 79
  • can you provide some explanation behind why this is happening in your example? I would think that the second call would also return 555. – wmock Feb 27 '13 at 15:28
  • @WillsonMock Good question. I would almost open up a new SO question for this. I found the answer back when I wrote this, but now I don't remember it any more and can't find it again. Should have posted it in the answer here too :-/ Happens with classes too btw. not just modules. – Casper Feb 27 '13 at 17:38
  • 2
    cool, in case you want to follow, this is the new SO question I've posted: http://stackoverflow.com/questions/15119724/ruby-lexical-scope-vs-inheritance – wmock Feb 27 '13 at 18:40