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.
local_variables.include?(:variable)
variable
: This is the variable we are checking to see if it is defined.
The value returned is a Boolean value. The method returns true
if the variable is defined. Otherwise, it returns false
.
# 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
In the code above: