Ruby Programming/Syntax/Variables and Constants

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

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


Contents

[edit] Local Variables

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

[edit] 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.

[edit] Class Variables

Example:

@@foobar

[edit] 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.

[edit] 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 substitute the value of a constant or trying to access an uninitialized constant raises the NameError exception.

[edit] Pseudo Variables

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

Previous: Lexicology Index Next: Literals

[edit] Pre-defined Variables

$!         The exception information message set by 'raise'.
$@         Array of 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 bracket matched by the last successful match.
$1 to $9   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.
$/         The input record separator, newline by default.
$\         The output record separator for the print and IO#write. Default is nil.
$,         The output field separator for the print and Array#join.
$;         The default separator for String#split.
$.         The current input line number of the last file that was read.
$<         The virtual concatenation file of the files given on command line.
$>         The default output for print, printf. $stdout by default.
$_         The last input line of string by gets or readline.
$0         Contains the name of the script being executed. May be assignable.
$*         Command line arguments given for the script sans args.
$$         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.
$"         The array contains the module names loaded by require.
$DEBUG     The status of the -d switch.
$FILENAME  Current input file from $<. Same as $<.filename.
$LOAD_PATH The alias to the $:.
$stderr    The current standard error output.
$stdin     The current standard input.
$stdout    The current standard output.
$VERBOSE   The verbose flag, which is set by the -v switch.
$-0        The alias to $/.
$-a        True if option -a ("autosplit" mode) is set. Read-only variable.
$-d        The alias to $DEBUG.
$-F        The alias to $;.
$-i        If in-place-edit mode is set, this variable holds the extension, otherwise nil.
$-I        The alias to $:.
$-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.
$-v        The alias to $VERBOSE.
$-w        True if option -w is set.

This infestation 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.

Personal tools
Create a book