# Ruby constant lookup for classes in modules

**URL:** <https://www.ruby-forum.com/t/ruby-constant-lookup-for-classes-in-modules/194202>\
**Category:** Ruby\
**Created:** [September 1, 2010, 2:10am UTC](https://www.ruby-forum.com/t/ruby-constant-lookup-for-classes-in-modules/194202 "2010-09-01T02:10:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![giaco](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/a3d4f5/32.png) [@giaco](https://www.ruby-forum.com/u/giaco)\
**Post date:** [September 1, 2010, 2:10am UTC](https://www.ruby-forum.com/t/ruby-constant-lookup-for-classes-in-modules/194202/1 "2010-09-01T02:10:03Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![giaco](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/a3d4f5/32.png) [@giaco](https://www.ruby-forum.com/u/giaco)\
**Post date:** [September 1, 2010, 12:31pm UTC](https://www.ruby-forum.com/t/ruby-constant-lookup-for-classes-in-modules/194202/2 "2010-09-01T12:31:09Z")

</div>

On Sep 1, 1:09 am, Jack C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> def f
> 
> ```
> 
> 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.
