How to check if a variable is defined in Ruby

Overview

A variable is defined if it is initialized. An initialized variable is a variable that contains a value. When a variable is undefined, it means that it contains no value. We can check if a value is defined or undefined in Ruby using the local_variables.include?(:) method.

Syntax

local_variables.include?(:variable)
Syntax for defined() method in Ruby

Parameters

variable: This is the variable we are checking to see if it is defined.

Return value

The value returned is a Boolean value. The method returns true if the variable is defined. Otherwise, it returns false.

Code

# create some variables that are defined
var1 = 30
var2 = "Hello"
var3 = 23
# check
puts local_variables.include?(:var1) # true
puts local_variables.include?(:var2) # true
puts local_variables.include?(:var3) # true
puts local_variables.include?(:var4) # false
puts local_variables.include?(:var5) # false

Explanation

In the code above:

  • Lines 2–4: We create some variables and initialize them with some values.
  • Lines 7–11: We check several variables, including ones we created and ones we didn't, to see if they are defined or undefined. Then, we print the results to the console.

Free Resources