Ruby Predefined Variables
Ruby Predefined Variables
Section titled “Ruby Predefined Variables”Ruby provides a set of special predefined global variables. Many of these have short, cryptic names (often involving punctuation like $ followed by a character). While they can be convenient for short scripts or quick debugging in IRB, their use in larger applications or libraries is generally discouraged due to their global nature and potential for reducing code readability.
Many of these variables have more readable alternatives, either through standard methods or by requiring the English module (require 'English'), which provides descriptive aliases.
Below is a table of common predefined variables, their English module aliases (if available), and descriptions:
| Variable | English Alias | Description |
|---|---|---|
| $! | $ERROR_INFO | The last exception object raised. Set by rescue. nil if no exception. |
| $@ | $ERROR_POSITION | The stack backtrace for the last exception raised (an array of strings). Use exception.backtrace for a specific exception object. |
| $_ | $LAST_READ_LINE | The last string read by gets or readline in the current scope. |
| $. | $INPUT_LINE_NUMBER, $NR | The current input line number of the last file read by gets or from ARGF. |
| $/ | $INPUT_RECORD_SEPARATOR, $RS | The input record separator (a string, newline \n by default). gets reads up to this separator. |
| $\ | $OUTPUT_RECORD_SEPARATOR, $ORS | The output record separator for print and IO#write ( nil by default). If set, it’s printed after each output. |
| $, | $OUTPUT_FIELD_SEPARATOR, $OFS | The output separator for print’s arguments and Array#join’s default (nil by default). |
| $; | $FIELD_SEPARATOR, $FS | The default separator for String#split when no argument is given (nil by default, which means split by whitespace). |
| $~ | $LAST_MATCH_INFO | A MatchData object from the last successful regular expression match in the current scope. Use Regexp.last_match for global last match. |
| $` | $PREMATCH | The string to the left of the last successful regex match. From Regexp.last_match.pre_match. |
| $& | $MATCH | The string matched by the last successful regex match. From Regexp.last_match[0]. |
| $‘ | $POSTMATCH | The string to the right of the last successful regex match. From Regexp.last_match.post_match. |
| $+ | $LAST_PAREN_MATCH | The text of the highest-numbered group matched by the last successful regex match. |
| $1, $2, … $N | N/A | The text of the Nth group captured by the last successful regex match. E.g., $1 is Regexp.last_match[1]. |
| $0 | $PROGRAM_NAME | The name of the Ruby script file currently being executed. |
| $* | $ARGV | Alias for ARGV, the array of command-line arguments passed to the script. |
| $$ | $PROCESS_ID, $PID | The process ID (PID) of the currently running Ruby script. |
| $? | $CHILD_STATUS | The exit status of the last executed child process (a Process::Status object). |
| $LOAD_PATH, $: | $LOAD_PATH | An array of directories Ruby searches when loading files with require or load. |
| $“ | $LOADED_FEATURES | An array of filenames of features that have been loaded (required). |
| $DEBUG | $DEBUG | A flag indicating if Ruby is running in debug mode (set by the -d command-line option). true or false. |
| $VERBOSE | $VERBOSE | The current verbosity level. nil (silent), false (normal), true (verbose). Set by -w or -v options. |
| $stdin | $stdin | The standard input stream object (default is STDIN). |
| $stdout | $stdout | The standard output stream object (default is STDOUT). |
| $stderr | $stderr | The standard error stream object (default is STDERR). |
| $SAFE (Deprecated) | N/A | The safe level. Deprecated in Ruby 2.7 and removed in Ruby 3.0. It had values 0-4 to control security restrictions. |
| $-a, $-d, $-F, $-I, $-l, $-p, $-v, $-w, $-0 | N/A | These variables reflect the state of various command-line options passed to the Ruby interpreter. For example, $-d is an alias for $DEBUG. |
Example Usage (with caution):
Section titled “Example Usage (with caution):”#!/usr/bin/env rubyrequire 'English'
# Example of using $~ and $1 after a match"hello world".match(/(\w+) (\w+)/)puts "Full match ($& or $MATCH): #{$MATCH}"puts "First capture ($1): #{$1}"puts "Second capture ($2): #{$2}"
# Example of using $! and $@ in a rescue blockbegin 1 / 0rescue ZeroDivisionError puts "Error type ($! or $ERROR_INFO): #{$ERROR_INFO.class}" puts "Error message: #{$ERROR_INFO.message}" puts "Backtrace ($@ or $ERROR_POSITION):" $ERROR_POSITION.first(2).each { |line| puts " #{line}" }end
puts "Script name ($0 or $PROGRAM_NAME): #{$PROGRAM_NAME}"puts "Arguments ($* or $ARGV): #{$ARGV.inspect}"puts "PID ($$ or $PROCESS_ID): #{$PROCESS_ID}"Best Practices:
Section titled “Best Practices:”- Prefer explicit methods and objects: Instead of relying on
$!, use the exception object passed torescue => e. ForMatchData, assign the result ofString#matchto a variable. - Use the
Englishmodule: If you find yourself needing these global variables,require 'English'can make your code much more readable by providing descriptive aliases (e.g.,$ERROR_INFOinstead of$!). - Limit scope: If used, their impact should be understood and contained, typically within very small scripts or specific local contexts.
- Avoid modifying most of them: While some (like
$/or$,) can be changed, modifying global state can lead to unexpected behavior in larger programs or libraries.
Many of these variables are remnants from Perl’s influence on Ruby’s early design. Modern Ruby style favors more explicit and object-oriented approaches.
For further details, consult the official Ruby documentation on predefined variables: https://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/globalvars.html