const = :FOO FOO = :ok defined? FOO => 'constant' How to check if FOO is defined using const?
defined? eval( const.to_s ) does not work.
Use const_defined? instead: http://ruby-doc.org/core/classes/Module.html#M000487
Object.const_defined?(const.to_s) to_s on the value supplied to Object.const_defined? is good practice for any generalized solution. For example: ruby >>> Object.const_get(nil) # => TypeError: no implicit conversion of nil into String >>> Object.const_get(nil.to_s) # => NameError: wrong constant name >>> Object.const_get(Hash) # => TypeError: no implicit conversion of Class into String >>> Object.const_get(Hash.to_s) # => Hash const = :FOO FOO = :OK defined?(FOO) # => "constant" instance_eval("defined?(#{const})") # => "constant" This will evaluate the statement, and gets around limitations to how defined? works in that it does not evaluate anything, so we have to evaluate it before it gets the instruction to call defined?.
Your eval is simply in the wrong order.
eval like you originally posted.
defined? FOO, notObject.const_defined? :FOOthat is required here. The key phrase in the question is "by its symbol", by which it differs from the linked question.defined?) will not work if you have the constant name stored in a string/symbol variable and want to know if it is defined. i.e.v = 'MyConstant'; defined? v; # => "local-variable"regardless of whetherMyConstantis defined or not. Likewisedefined? v.constantize; # => "method"regardless. Collin Graves accepted answer, withObject.const_defined?, is a good workaround.