开发者

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

开发者 https://www.devze.com 2023-03-14 06:35 出处:网络
I can access the constant AGE as A::AGE. How do I access the constant NAME?(as A::NAME throws an error.)

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


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.


Define the constant with:

self::NAME = "foo"

This will explicitly bind it to self.

0

精彩评论

暂无评论...
验证码 换一张
取 消