# Constant lookup when using namespaces

**URL:** <https://www.ruby-forum.com/t/constant-lookup-when-using-namespaces/157464>\
**Category:** Ruby\
**Created:** [January 11, 2009, 9:35pm UTC](https://www.ruby-forum.com/t/constant-lookup-when-using-namespaces/157464 "2009-01-11T21:35:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [January 11, 2009, 9:35pm UTC](https://www.ruby-forum.com/t/constant-lookup-when-using-namespaces/157464/1 "2009-01-11T21:35:48Z")

</div>

Here is an example.

#!/usr/bin/ruby

class A

end

class A::B

def method\_one  
x = C.new  
puts x.blah  
end

end

class A::C

def blah  
puts “I want this one”  
end  
end

class C

def blah  
puts “this is the wrong one”  
end

end

ab = A::B.new  
ab.method\_one

As you can see when you run it you get the blah out of ::C NOT A::C  
which I was expecting. Is there a way to be able to say C.new inside  
of A::B and have it check the A:: Namespace first?

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [January 11, 2009, 9:44pm UTC](https://www.ruby-forum.com/t/constant-lookup-when-using-namespaces/157464/2 "2009-01-11T21:44:05Z")

</div>

On Jan 11, 2009, at 3:34 PM, removed\_email\_address@domain.invalid wrote:

> Here is an example.
> 
> #!/usr/bin/ruby
> 
> class A
> 
> end
> 
> class A  
> class B
> 
> def method\_one  
> x = C.new  
> puts x.blah  
> end

end

> end
> 
> class A  
> class C
> 
> def blah  
> puts “I want this one”  
> end  
> end
> 
> ab = A::B.new  
> ab.method\_one
> 
> As you can see when you run it you get the blah out of ::C NOT A::C  
> which I was expecting. Is there a way to be able to say C.new inside  
> of A::B and have it check the A:: Namespace first?

I don’t remember the details of “why”, but “class A::C; end” opens the  
A:: scope differently from “class A; class C; end; end”. When you  
make the “class A” namespace explicit, you get the behavior you were  
expecting.

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid
