B Seven
B Seven

Reputation: 45941

How to check if a constant is defined by its symbol in Ruby?

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

Answers (2)

vgoff
vgoff

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

Collin Graves
Collin Graves

Reputation: 2267

Use const_defined? instead: http://ruby-doc.org/core/classes/Module.html#M000487

Object.const_defined?(const.to_s)

Upvotes: 34

Related Questions