Ruby constant in class method

class A class << self CONST = 1 end end puts A::CONST # this doesn't work 

Is there a way to access the constant from outside the class using this self class call?

This effectively does:

 class A self.CONST = 1 end 

I understand that I can simply move the constant from this self-start to easily solve this problem. I'm more curious about the inner workings of a ruby.

+8
ruby
source share
3 answers

Not quite what you wanted, but you just did not define CONST inside class A, but in your metaclass, which I therefore saved a link to ...

 class A class << self ::AA = self CONST = 1 end end puts AA::CONST 
+4
source share

Your problem is that you are mistaken in the meaning of the code.

 class << self FOO = :bar end 

not equivalent to self.FOO = :bar . This is very different from this. This is equivalent to self.singleton_class.const_set(:FOO, :bar) .

I think you are assuming that class << self means "suggesting there is an implicit" I "in front of everything that I write here" or something like that (maybe you are thinking of JavaScript with ). In fact, this means that we put ourselves in the context of the self singleton class, whose special class is the only instance of the current object. Thus, you define a constant in the Singleton class of the class.

To define a constant in a class, simply write:

 class Something FOO = :bar end 
+4
source share

Also, maybe not quite what you wanted, since your reference class A is in a metaclass (which seems like a trick), but a little more concise.

  class A class << self A::CONST = 1 end end 

For a deep understanding of what is happening in this post, it is rather informative http://www.klankboomklang.com/2007/10/05/the-metaclass/

+1
source share

All Articles