Given defined and undefined variables and we have to check variables are defined or not.
Ruby provides you multiple ways to check the existence of a variable in your code. We have included two of them in this program. The ways are different so as their return types. It's up to you how you take the path for making your logic better for nice program code. Now, let us go through both methods.
- puts:
This method is used to display some kind of message for the user.
- .defined?:
This method returns the type of variable like local or instance. It will not return anything if the variable is not defined in the program code.
- .include?:
This method returns value as true or false. It requires the type of variable to know whether it is defined or not. .include? the method has got many functionalities. It is used in arrays as well.
Ruby code to check whether a variable is defined or not
Method 1:
Output
Method 2:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer