Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a variable is defined?

How can I check whether a variable is defined in Ruby? Is there an isset-type method available?

like image 278
readonly Avatar asked Nov 13 '08 23:11

readonly


People also ask

How do you check if a variable is not defined?

To check if a variable is undefined, you can use comparison operators — the equality operator == or strict equality operator === . If you declare a variable but not assign a value, it will return undefined automatically. Thus, if you try to display the value of such variable, the word "undefined" will be displayed.

How do you check if a Python variable is defined?

To check if the variable is defined in a local scope, you can use the locals() function, which returns a dictionary representing the current local symbol table. if 'x' in locals(): print('Variable exist. ')

How do you know if a variable is undefined or null?

Finally, the standard way to check for null and undefined is to compare the variable with null or undefined using the equality operator ( == ). This would work since null == undefined is true in JavaScript. That's all about checking if a variable is null or undefined in JavaScript.

How do you check if a variable is not defined Python?

Python doesn't have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use, even if initially assigned the None object.


1 Answers

Use the defined? keyword (documentation). It will return a String with the kind of the item, or nil if it doesn’t exist.

>> a = 1  => 1 >> defined? a  => "local-variable" >> defined? b  => nil >> defined? nil  => "nil" >> defined? String  => "constant" >> defined? 1  => "expression" 

As skalee commented: "It is worth noting that variable which is set to nil is initialized."

>> n = nil   >> defined? n  => "local-variable" 
like image 160
Ricardo Acras Avatar answered Oct 21 '22 13:10

Ricardo Acras