Reputation: 45941
const = :FOO
FOO = :ok
defined? FOO => 'constant'
How to check if FOO
is defined using const
?
defined? eval( const.to_s )
does not work.
Upvotes: 18
Views: 14035
Reputation: 11343
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.
Upvotes: 1
Reputation: 2267
Use const_defined?
instead: http://ruby-doc.org/core/classes/Module.html#M000487
Object.const_defined?(const.to_s)
Upvotes: 34