Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby constant within a class method

Tags:

ruby

 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.

like image 987
djburdick Avatar asked Mar 09 '11 18:03

djburdick


1 Answers

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
like image 144
DigitalRoss Avatar answered Sep 21 '22 18:09

DigitalRoss