Ruby constant lookup for classes in modules

What's the difference between defining a class inside of a module and using the module as a prefix?

module Foo
   class Bar
   end
end

module Foo
   class Works
     def f
       Bar.new
     end
   end
end

class Foo::Fails
   def f
     Bar.new
   end
end

Foo::Works.new.f
Foo::Fails.new.f

The last line fails:

lookup.rb:16:in `f': uninitialized constant Foo::Fails::Bar (NameError)
     from lookup.rb:21

I would have thought that both ways of placing a class in a module would be equivalent.

Thanks.

Jack

Hi Jack,

I believe the difference is one of scope:

module Foo
  class Works

means "put Works in the namespace of Foo" and "define Works in the
scope of the module Foo", and hence 'Bar' is accessible.

class Foo::Fails

means, "put Fails in the namespace of Foo" but "define Fails in the
current scope", and hence 'Bar' is not accessible.

Hope that helps,

  Peter.

···

On Sep 1, 1:09 am, Jack Christensen <j...@jackchristensen.com> wrote:

What's the difference between defining a class inside of a module and
using the module as a prefix?

module Foo
class Bar
end
end

module Foo
class Works
def f
Bar.new
end
end
end

class Foo::Fails
def f
Bar.new
end
end

Foo::Works.new.f
Foo::Fails.new.f

The last line fails:

lookup.rb:16:in `f': uninitialized constant Foo::Fails::Bar (NameError)
from lookup.rb:21

I would have thought that both ways of placing a class in a module would
be equivalent.

Thanks.

Jack