determine if a constant is defined

  1. use the Ruby built-in: defined?  It works for constants, methods, classes, etc.
  2. self.class.const_defined?(:My_Constant)

There is no better among these two choices. Choosing which one depends on the user case. The second way specifies the scope to check if the constant exists, while the first way will seek for this constant through the ancestor trees. If you defines two constants with the same name but different values, you’d better use the 2nd way.


  • scope of constants:Ruby searches for the constant definition in this order:
    1. The enclosing scope
    2. Any outer scopes (repeat until top level is reached)
    3. Included modules
    4. Superclass(es)
    5. Object
    6. Kernel

better read:

class C
  X = 1
  module M
    X = 2
    class D
      X = 3
      puts X          # => 3
      puts C::X       # => 1
      puts C::M::X    # => 2
      puts M::X       # => 2    

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s