Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Ruby Keyword: defined?

ConradIrwin edited this page · 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 https://github.com/rking/pry-docmore/wiki

Something went wrong with that request. Please try again.