Harish Shetty
Harish Shetty

Reputation: 64373

Ruby: How to access the constant defined in a anonymous class?

I can access the constant AGE as A::AGE. How do I access the constant NAME?(as A::NAME throws an error.)

class A
  AGE=24
  class << self
    NAME="foo"
  end
end

Note: I am trying to access the constants outside the class A.

Note 2: I am on Ruby 1.8.7

Upvotes: 3

Views: 846

Answers (2)

mliebelt
mliebelt

Reputation: 15525

In Ruby 1.9.x, Ruby provides the method singleton_class. So the call

irb(main):009:0> A.singleton_class::NAME
=> "foo"

does what you want to do.


In Ruby 1.8.x, you may implement the method singleton_class on your own:

class Object
  def singleton_class
    class << self; self; end
  end
end

Then you are able to call:

A.singleton_class::NAME
=> "foo"

This is possible due to the fact that Ruby classes are all the time open for extensions and changes.

Upvotes: 9

d11wtq
d11wtq

Reputation: 35318

Define the constant with:

self::NAME = "foo"

This will explicitly bind it to self.

Upvotes: 1

Related Questions