# Getting a constant inside a class

**URL:** <https://www.ruby-forum.com/t/getting-a-constant-inside-a-class/149001>\
**Category:** Ruby\
**Created:** [September 19, 2008, 8:14am UTC](https://www.ruby-forum.com/t/getting-a-constant-inside-a-class/149001 "2008-09-19T08:14:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![benjohnson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@benjohnson](https://www.ruby-forum.com/u/benjohnson)\
**Post date:** [September 19, 2008, 8:14am UTC](https://www.ruby-forum.com/t/getting-a-constant-inside-a-class/149001/1 "2008-09-19T08:14:50Z")

</div>

How do you grab the value of a constant if it is inside a class \<\< self?

example

class A  
class \<\< self  
B = “HI”  
end  
end

A::B does not work. How would you go about grabbing the value for B?  
Sorry for such a noob question. Thanks!

---

<div class="post-metadata">

**Author:** ![benjohnson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@benjohnson](https://www.ruby-forum.com/u/benjohnson)\
**Post date:** [September 19, 2008, 12:23pm UTC](https://www.ruby-forum.com/t/getting-a-constant-inside-a-class/149001/2 "2008-09-19T12:23:08Z")

</div>

Ben J. wrote:

> How do you grab the value of a constant if it is inside a class \<\< self?
> 
> example
> 
> class A  
> class \<\< self  
> B = “HI”  
> end  
> end
> 
> A::B does not work. How would you go about grabbing the value for B?

You’ve explicitly defined the constant inside the metaclass (singleton  
class) of A.

I’d say it’s better not to define the constant there in the first place,  
but define it under A:

irb(main):001:0\> class A  
irb(main):002:1\> B = “HI”  
irb(main):003:1\> class \<\< self  
irb(main):004:2\> def test  
irb(main):005:3\> puts “I say #{B}”  
irb(main):006:3\> end  
irb(main):007:2\> end  
irb(main):008:1\> end  
=\> nil  
irb(main):009:0\> A.test  
I say HI  
=\> nil  
irb(main):010:0\> A::B  
=\> “HI”

But if you _really_ want to store a constant in a metaclass, it _is_  
possible to get at it:

irb(main):001:0\> class A  
irb(main):002:1\> class \<\< self  
irb(main):003:2\> B = “HI”  
irb(main):004:2\> end  
irb(main):005:1\> end  
=\> “HI”  
irb(main):006:0\> A::B  
NameError: uninitialized constant A::B  
from (irb):6  
from :0  
irb(main):007:0\> class Class  
irb(main):008:1\> def meta  
irb(main):009:2\> class \<\<self; self; end  
irb(main):010:2\> end  
irb(main):011:1\> end  
=\> nil  
irb(main):012:0\> A.meta::B  
=\> “HI”

I wrote a SingletonTutorial on the [rubygarden.org](http://rubygarden.org) wiki, but  
unfortunately that site appears to have closed.

Regards,

Brian.
