Ruby Programming/Syntax/Variables and Constants

A variable in Ruby can be distinguished by the characters at the start of its name. There's no restriction to the length of a variable's name (with the exception of the heap size).

Summary
The first character indicates the scope:
 * Local variables - lowercase letter or underscore
 * Instance variables - @
 * In class scope, instance variables belong to the object that is the class
 * To define instance variables on the objects that belong to the class, use @ inside initialize
 * Class variables - @@
 * Global variables - $
 * Constants - uppercase letter

For more information on variable scopes related to classes, see Ruby Programming/Syntax/Classes.

Local Variables
Example: foobar _foobar A variable whose name begins with a lowercase letter (a-z) or underscore (_) is a local variable or method invocation.

A local variable is only accessible from within the block of its initialization. For example: i0 = 1 loop { i1 = 2 puts defined?(i0)	# true; "i0" was initialized in the ascendant block puts defined?(i1)	# true; "i1" was initialized in this block break } puts defined?(i0)	# true; "i0 was initialized in this block puts defined?(i1)	# false; "i1" was initialized in the loop

Instance Variables
Example: @foobar A variable whose name begins with '@ ' is an instance variable of self. An instance variable belongs to the object itself. Uninitialized instance variables have a value of nil.

Class Variables
A class variable is shared by all instances of a class and begins with '@@'. Example: @@foobar

An important note is that the class variable is shared by all the descendants of the class. Example:

This shows us that all our classes were changing the same variable. Class variables behave like global variables which are visible only in the inheritance tree. Because Ruby resolves variables by looking up the inheritance tree *first*, this can cause problems if two subclasses both add a class variable with the same name.

Global Variables
Example: $foobar A variable whose name begins with '$ ' has a global scope; meaning it can be accessed from anywhere within the program during runtime.

Constants
Usage: FOOBAR A variable whose name begins with an uppercase letter (A-Z) is a constant. A constant can be reassigned a value after its initialization, but doing so will generate a warning. Every class is a constant.

Trying to access an uninitialized constant raises the NameError exception.

How constants are looked up
Constants are looked up based on your scope or via the scope resolution operator (i.e. '::'). For example

class A   A2 = 'a2' class B     def go        A2       end end end instance_of_b = A::B.new a2 = A::A2

Another example class Foo BAR = 123 end puts Foo::BAR
 * 1) => 123

Pseudo Variables

 * Execution context of the current method, which could refer to an instance, class, or module.


 * The sole-instance of the  class. Expresses nothing.


 * The sole-instance of the  class. Expresses true.


 * The sole-instance of the  class. Expresses false.


 * These are contents of capturing groups for regular expression matches. They are local to the current thread and stack frame!

(nil also is considered to be false, and every other value is considered to be true in Ruby.) The value of a pseudo variable cannot be changed. Substitution to a pseudo variable causes an exception to be raised.

Pre-defined Variables
Many pre-defined variables are useful when dealing with regular expressions or Ruby interpreter parameters.

{| class="wikitable" ! Name !! Aliases !! Description
 * || || The exception information message set by the last 'raise' (last exception thrown).
 * || || Array of the backtrace of the last exception thrown.
 * || || The string matched by the last successful pattern match in this scope.
 * || || The string to the left of the last successful match.
 * || || The string to the right of the last successful match.
 * || || The last group of the last successful match.
 * to  ||  || The Nth group of the last successful regexp match.
 * || || The information about the last match in the current scope.
 * || || The flag for case insensitive, nil by default (deprecated).
 * ||,  or   || The input record separator, newline by default.
 * || or  || The output record separator for the print and IO#write. Default is nil.
 * || or  || The output field separator for the print and Array#join.
 * ||,  or   || The default separator for String#split.
 * || or  || The current input line number of the last file that was read.
 * || || An object that provides access to the concatenation of the contents of all the files given as command-line arguments, or $stdin (in the case where there are no arguments). Read only.
 * ||  ||  || The destination of output for Kernel.print and Kernel.printf. The default value is $stdout.
 * || || The last input line of string by gets or readline.
 * ||  ||  || Command line arguments given for the script.  Also known as
 * ||,  or   || The process number of the Ruby running this script.
 * || || The status of the last executed child process.
 * ||  || Load path for scripts and binary modules by load or require.
 * ||  or   || The array contains the module names loaded by require.
 * ||  ||   ||   ||   || The status of the -d switch.  Assignable.
 * ||  || Character encoding of the source code.
 * ||  || The verbose flag, which is set by the -v switch.
 * ||  ||   ||   ||   ||  " which defines the longer names listed in the table above. To include these names, just require the English library as follows.
 * || or  || The current input line number of the last file that was read.
 * || || An object that provides access to the concatenation of the contents of all the files given as command-line arguments, or $stdin (in the case where there are no arguments). Read only.
 * ||  ||  || The destination of output for Kernel.print and Kernel.printf. The default value is $stdout.
 * || || The last input line of string by gets or readline.
 * ||  ||  || Command line arguments given for the script.  Also known as
 * ||,  or   || The process number of the Ruby running this script.
 * || || The status of the last executed child process.
 * ||  || Load path for scripts and binary modules by load or require.
 * ||  or   || The array contains the module names loaded by require.
 * ||  ||   ||   ||   || The status of the -d switch.  Assignable.
 * ||  || Character encoding of the source code.
 * ||  || The verbose flag, which is set by the -v switch.
 * ||  ||   ||   ||   ||  " which defines the longer names listed in the table above. To include these names, just require the English library as follows.
 * || || The status of the last executed child process.
 * ||  || Load path for scripts and binary modules by load or require.
 * ||  or   || The array contains the module names loaded by require.
 * ||  ||   ||   ||   || The status of the -d switch.  Assignable.
 * ||  || Character encoding of the source code.
 * ||  || The verbose flag, which is set by the -v switch.
 * ||  ||   ||   ||   ||  " which defines the longer names listed in the table above. To include these names, just require the English library as follows.
 * ||  || Character encoding of the source code.
 * ||  || The verbose flag, which is set by the -v switch.
 * ||  ||   ||   ||   ||  " which defines the longer names listed in the table above. To include these names, just require the English library as follows.
 * ||  || The verbose flag, which is set by the -v switch.
 * ||  ||   ||   ||   ||  " which defines the longer names listed in the table above. To include these names, just require the English library as follows.
 * ||  ||   ||   ||   ||  " which defines the longer names listed in the table above. To include these names, just require the English library as follows.

Without ‘English’:

$\ = ' -- '   "waterbuffalo" =~ /buff/ print $", $', $$, "\n"

With English:

require "English" $OUTPUT_FIELD_SEPARATOR = ' -- ' "waterbuffalo" =~ /buff/ print $LOADED_FEATURES, $POSTMATCH, $PID, "\n"

Pre-defined Constants
Note that there are some pre-defined constants at parse time, as well, namely __FILE__  (current file) __LINE__  (current line) and __dir__   (current directory) __method__ (current method) (new in Ruby 2.0)

A list of predefined global constants can be found in the Ruby language documentation. Among the notable ones are: