Skip to content
instance method

Module#const_defined?

(::interned name, ?::boolish inherit) -> bool
mod.const_defined?(sym, inherit=true) → true or false
mod.const_defined?(str, inherit=true) → true or false

Says whether mod or its ancestors have a constant with the given name:

Example
Float.const_defined?(:EPSILON)      #=> true, found in Float itself
Float.const_defined?("String")      #=> true, found in Object (ancestor)
BasicObject.const_defined?(:Hash)   #=> false

If mod is a Module, additionally Object and its ancestors are checked:

Example
Math.const_defined?(:String)   #=> true, found in Object

In each of the checked classes or modules, if the constant is not present but there is an autoload for it, true is returned directly without autoloading:

Example
module Admin
  autoload :User, 'admin/user'
end
Admin.const_defined?(:User)   #=> true

If the constant is not found the callback const_missing is not called and the method returns false.

If inherit is false, the lookup only checks the constants in the receiver:

Example
IO.const_defined?(:SYNC)          #=> true, found in File::Constants (ancestor)
IO.const_defined?(:SYNC, false)   #=> false, not found in IO itself

In this case, the same logic for autoloading applies.

If the argument is not a valid constant name a NameError is raised with the message “wrong constant name name”:

Example
Hash.const_defined? 'foobar'   #=> NameError: wrong constant name foobar
See also #constants #const_get #const_added #const_missing also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0