How to Check Nil Object in Ruby
Ruby allows the programmer to access data using named variables that point to a location in memory. Normally, this works fine, but sometimes an error or other event can cause the variable to point to "nil," a special data type that lets the programmer know that the variable does not point to any data. Programmers can check for nil and react to it appropriately using a special method that all variables inherit.
Instructions
-
-
1
Open a terminal. In Windows, click "Start," "Run" and type "cmd." In Mac OS X, click the Spotlight icon and type "Terminal."
-
2
Type "irb" into the terminal to open the interactive Ruby interpreter.
-
-
3
Type the following into the terminal to define a variable as nil in Ruby:
d = nil
-
4
Type the following to check if a variable is nil:
d.nil?
The result will be either "true" or "false."
-
1
Tips & Warnings
"nil?" will check if a variable is nil, but will still generate an error if it is run on a variable that was never defined at all. In order to check if a variable is defined, you must use the "defined?" operator. Type the following to do so: "defined? d".