8
 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 with this self class call?

It is effectively doing this:

class A
    self.CONST = 1
end

I understand that I can just move the constant out of this self call to easily solve this problem. I'm more curious about the inner workings of ruby.

djburdick
  • 11,762
  • 9
  • 46
  • 64

3 Answers3

4

Not exactly what you wanted, but you simply haven't defined CONST inside class A but in its metaclass, which I have therefore saved a reference to...

class A
  class << self
    ::AA = self
    CONST = 1
  end
end
puts AA::CONST
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
4

Your problem is that you're mistaken about the meaning of the code.

class << self
  FOO = :bar
end

is not equivalent to self.FOO = :bar. It's extremely different from that. It is equivalent to self.singleton_class.const_set(:FOO, :bar).

I think you're assuming that class << self means "assume there's an implicit 'self' before everything I write here" or something along those lines (maybe you're thinking of JavaScript's with statement). What it actually does is take put us into the context of the self's singleton class, a special class of which the current object is the only instance. So you're defining the constant on the object's singleton class.

To define a constant on a class, you just write:

class Something
  FOO = :bar
end
Chuck
  • 234,037
  • 30
  • 302
  • 389
  • Thanks! I don't see how self.method and class << self are different. They are both singleton methods. Please see question here if you have a chance: http://stackoverflow.com/questions/5508351/in-ruby-whats-the-difference-between-self-method-and-a-method-within-class-se – djburdick Apr 01 '11 at 01:43
1

Also probably not exactly what you wanted, since your referencing class A in A's metaclass (which seems kind of a cheat), but it is slightly more concise.

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

For a in depth understanding of what's going on this post is pretty informative http://www.klankboomklang.com/2007/10/05/the-metaclass/

forforf
  • 895
  • 7
  • 14