How to use the "defined?" keyword in Ruby?

Ruby provides a special keyword known as defined? that is used to determine if a particular object or data type is defined in Ruby or not.

The defined? keyword will return a string describing its expression or argument, if the passed expression or argument is defined. It returns nil if the expression or the argument is not defined in Ruby.


The syntax of the defined keyword in Ruby is given below

defined? variable_name

Now, let's take a couple of examples to demonstrate how to use the defined keyword in Ruby.

Example 1

Consider the code shown below.

# Declare the Variables
programming = 2
ruby = programming * 2

# Checking if the variables are defined or not
var1 = defined? programming
var2 = defined? java
var3 = defined? ruby
var4 = defined? Math::PI

# Displaying the results
puts "Variable 1: #{var1}"
puts "Variable 2: #{var2}"
puts "Variable 3: #{var3}"
puts "Variable 4: #{var4}"


It will produce the following output.

Variable 1: local-variable
Variable 2:
Variable 3: local-variable
Variable 4: constant

In this code, we declared two local variables and then used a constant from the Math module, that's why we got the respective string outputs for them.

In case of "Variable 2", we passed a string name that wasn't declared at all, hence we got nil as the output.

Example 2

Now let's explore a more complicated Ruby code that contains a module and two methods, where one method is defined in a module and the other one isn't. Consider the code shown below.

# Ruby program to illustrate defined? keyword

# First Method
def first_method
   puts "Learn Ruby Programming"

module Module1
   def second_method
      puts "Inside Coders"

# Checking if the method is defined or not
# Using defined? keyword
method1 = defined? first_method
method2 = defined? second_method
module1 = defined? Module1
method3 = defined? hello
method4 = defined? puts

# Displaying results
puts "Method 1: #{method1}"
puts "Method 2: #{method2}"
puts "Method 3: #{method3}"
puts "Method 4: #{method4}"
puts "Module 1: #{module1}"


It will produce the following output.

Method 1: method
Method 2:
Method 3:
Method 4: method
Module 1: constant