How to check if a variable is defined in Ruby
In this tutorial, we are going to learn about how to check if a given variable is defined or not in Ruby.
Using defined? keyword
In ruby, we can use the built-in defined?
keyword to check if a variable is defined or not.
The defined?
keyword returns the information about the expression if a variable is defined in the current scope; otherwise, it returns nil.
Here is an example:
year = 2021
puts defined? year
Output:
"local-variable"
second example:
puts defined? day
Output:
nil