Getting a constant inside a class

B

Ben Johnson

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!
 
B

Brian Candler

Ben said:
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 wiki, but
unfortunately that site appears to have closed.

Regards,

Brian.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,651
Latest member
VeraPiw932

Latest Threads

Top