Ruby Keyword: defined?

ConradIrwin edited this page Jan 6, 2013 · 4 revisions
Clone this wiki locally
defined? nil ⇒ "nil"
defined? self ⇒ "self"
defined? true ⇒ "true"
defined? false ⇒ "false"
defined? "asdf" ⇒ "expression"
defined? a = 3 ⇒ "assignment" # but doesn't actually set a to 3.
defined? printf ⇒ "method"
printf = 3
defined? printf ⇒ "local-variable" # nil if there is no local or method with that name
defined? $foo ⇒ "global-variable"  # nil if $foo has not been assigned to
defined? Object ⇒ "constant"       # nil if there is no constant with that name
defined? super ⇒ "super"           # nil if there is no super method.
defined? yield ⇒ "yield"           # nil if no block was passed to this method

defined? is most often used to determine whether a constant or global variable is defined. For example ruby-1.8.7 didn't have a RUBY_ENGINE constant, so jruby was often detected using:

defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"

Another idiomatic use is to safely call a super-method:

super if defined?(super)

It can be used to detect whether a block was passed to this method, though block_given? is usually preferred.

yield if defined?(yield)

Although the return value of defined? is a string, this is usually ignored and only the truthiness of the result considered.

Improve these docs at