How to Use the Ruby defined? Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby defined? method.

Using the defined? method

The defined? keyword in Ruby is used to determine whether or not a given expression has been defined. It is a unary operator, which means it only operates on a single operand.

Syntax

The syntax for the defined? keyword is as follows:

defined?(expression)

Here, expression is the operand that you want to check whether it is defined or not. It can be a variable, a method, a constant, or any other expression in Ruby.

The defined? keyword returns a string that describes the type of the expression, or nil if the expression is not defined. The possible values of the string are:

  • “local-variable”: if the expression is a local variable that has been initialized
  • “instance-variable”: if the expression is an instance variable of an object
  • “class-variable”: if the expression is a class variable of a class or module
  • “global-variable”: if the expression is a global variable
  • “method”: if the expression is a method that has been defined
  • “yield”: if the expression is inside a block that has been called with a yield statement
  • “super”: if the expression is inside a method that calls the super method
  • “module”: if the expression is a module that has been defined
  • “class”: if the expression is a class that has been defined
  • “constant”: if the expression is a constant that has been defined
  • “true”: if the expression is the true value
  • “false”: if the expression is the false value
  • “nil”: if the expression is the nil value
  • “self”: if the expression is the current object

Example

Here are some examples of how to use the defined? keyword in Ruby:

foo = 42
defined?(foo) # => "local-variable"

class Foo
  def bar
  end
end
defined?(Foo) # => "constant"
defined?(Foo.bar) # => "method"

$global_var = 42
defined?($global_var) # => "global-variable"

def baz
  yield if block_given?
end
defined?(yield) # => "yield"

class Bar
  def qux
    super
  end
end
defined?(super) # => "super"