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).


Local VariablesEdit

Example:

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 VariablesEdit

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 VariablesEdit

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:

class Parent
  @@foo = "Parent"
 end
 class Thing1 < Parent
   @@foo = "Thing1"
 end
 class Thing2 < Parent
   @@foo = "Thing2"
 end
 >>Parent.class_eval("@@foo")
 =>"Thing2"
 >>Thing1.class_eval("@@foo")
 =>"Thing2"
 >>Thing2.class_eval("@@foo")
 =>"Thing2"
 >>Thing2.class_variables
 =>[]
 Parent.class_variables
 =>[:@@foo]

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 VariablesEdit

Example:

$foobar

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

ConstantsEdit

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 upEdit

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   
# => 123

Pseudo VariablesEdit

self

Execution context of the current method.

nil

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

true

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

false

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

$1, $2 ... $9

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 VariablesEdit

Name Aliases Description
$! $ERROR_INFO[1] The exception information message set by the last 'raise' (last exception thrown).
$@ $ERROR_POSITION[1] Array of the backtrace of the last exception thrown.
$& $MATCH[1] The string matched by the last successful pattern match in this scope.
$` $PREMATCH[1] The string to the left of the last successful match.
$' $POSTMATCH[1] The string to the right of the last successful match.
$+ $LAST_PAREN_MATCH[1] The last bracket matched by the last successful match.
$1 to $9 The Nth group of the last successful regexp match.
$~ $LAST_MATCH_INFO[1] The information about the last match in the current scope.
$= $IGNORECASE[1] The flag for case insensitive, nil by default (deprecated).
$/ $INPUT_RECORD_SEPARATOR[1], $RS[1] or $-0 The input record separator, newline by default.
$\ $OUTPUT_RECORD_SEPARATOR[1] or $ORS[1] The output record separator for the print and IO#write. Default is nil.
$, $OUTPUT_FIELD_SEPARATOR[1] or $OFS[1] The output field separator for the print and Array#join.
$; $FIELD_SEPARATOR[1], $FS[1] or $-F The default separator for String#split.
$. $INPUT_LINE_NUMBER[1] or $NR[1] The current input line number of the last file that was read.
$< $DEFAULT_INPUT[1] 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.
$FILENAME Current input file from $<. Same as $<.filename.
$> $DEFAULT_OUTPUT[1] The destination of output for Kernel.print and Kernel.printf. The default value is $stdout.
$_ $LAST_READ_LINE[1] The last input line of string by gets or readline.
$0 Contains the name of the script being executed. May be assignable.
$* ARGV[1] Command line arguments given for the script. Also known as ARGV
$$ $PROCESS_ID[1], $PID[1] or Process.pid The process number of the Ruby running this script.
$? $CHILD_STATUS[1] The status of the last executed child process.
$: $LOAD_PATH Load path for scripts and binary modules by load or require.
$" $LOADED_FEATURES or $-I The array contains the module names loaded by require.
$stderr The current standard error output.
$stdin The current standard input.
$stdout The current standard output.
$-d $DEBUG The status of the -d switch. Assignable.
$-K $KCODE Character encoding of the source code.
$-v $VERBOSE The verbose flag, which is set by the -v switch.
$-a True if option -a ("autosplit" mode) is set. Read-only variable.
$-i If in-place-edit mode is set, this variable holds the extension, otherwise nil.
$-l True if option -l is set ("line-ending processing" is on). Read-only variable.
$-p True if option -p is set ("loop" mode is on). Read-only variable.
$-w True if option -w is set.

The use of cryptic two-character $? expressions is a thing that people will frequently complain about, dismissing Ruby as just another perl-ish line-noise language. Keep this chart handy. Note, a lot of these are useful when working with regexp code. Part of the standard library is "English" which defines longer names to replace the two-character variable names to make code more readable. The defined names are also listed in the table. To include these names, just require the English library as follows.[1]

Without ‘English’:

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

With English:

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

Pre-defined ConstantsEdit

Note that there are some pre-defined constants at parse time, as well, namely

 __FILE__ (current file)
 __LINE__ (current line)

and

 __dir__ (current directory)

(new in Ruby 2.0)

NotesEdit

  1. a b c d e f g h i j k l m n o p q r s t u v w x y z English.rb from the Ruby 1.9.2 Standard Library Documentation
Previous: Lexicology Index Next: Literals
Last modified on 1 February 2014, at 00:04