Search code examples
rubyconstantsruby-1.8.7class-constants

Right way to check if a constant is already defined in a Ruby Class


I have certain classes that are implemented as decorators in my Rails app which is on Ruby 1.8.7 . I keep getting the warning - warning: already initialized constant ABC . Here ABC is the name of the constant.

To solve this, I'm using the const_defined? method as suggested in this answer .

My doubt is - is const_defined? the right way to check if a class constant is already defined in ruby ? I clearly see that it can be used to check for a module constant.

I was able to see that the defined? method can also be used as mentioned in this answer. I tried to lookup the documentation of defined?, but I don't see a link to its documentation based on my search thus far.

I'm not sure which to choose among the two as I can't see a clear difference between the two at this point.

Could one please suggest which is best to use in this situation and why?.


Solution

  • The keyword defined? is documented here.

    It is better to ask if it is a constant, and use const_defined? if it is important that it is a constant. If you only care that it is defined, then use the keyword defined?