# Getting a constant inside a class

**URL:** <https://rubytalk.org/t/getting-a-constant-inside-a-class/49171>\
**Category:** ruby-talk\
**Created:** [19 September 2008 06:07 UTC](https://rubytalk.org/t/getting-a-constant-inside-a-class/49171 "2008-09-19T06:07:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ben\_Johnson](https://avatars.discourse-cdn.com/v4/letter/b/e8c25b/32.png) [@Ben\_Johnson](https://rubytalk.org/u/Ben_Johnson)\
**Post date:** [19 September 2008 06:07 UTC](https://rubytalk.org/t/getting-a-constant-inside-a-class/49171/1 "2008-09-19T06:07:20Z")

</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

Sorry for such a noob question. Thanks!

> **···**
>
> A::B does not work. How would you go about grabbing the value for B?  
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Brian\_Candler](https://avatars.discourse-cdn.com/v4/letter/b/5f9b8f/32.png) [@Brian\_Candler](https://rubytalk.org/u/Brian_Candler)\
**Post date:** [19 September 2008 10:15 UTC](https://rubytalk.org/t/getting-a-constant-inside-a-class/49171/2 "2008-09-19T10:15:27Z")

</div>

Ben Johnson 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  
&nbsp;&nbsp;from (irb):6  
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 wiki, but  
unfortunately that site appears to have closed.

Regards,

Brian.

> **···**
>
> from :0  
> --  
> Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).
