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 definedvar1 = 30var2 = "Hello"var3 = 23# checkputs local_variables.include?(:var1) # trueputs local_variables.include?(:var2) # trueputs local_variables.include?(:var3) # trueputs local_variables.include?(:var4) # falseputs 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.