411 REFERENCE · Wikibooks
Ruby Programming/Syntax/Variables and Constants
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
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:
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 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
# => 123
Pseudo Variables
self
Execution context of the current method, which could refer to an instance, class, or module.
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 Variables
Many pre-defined variables are useful when dealing with regular expressions or Ruby interpreter parameters.
Name Aliases Description $! $ERROR_INFOEnglish.rb from the Ruby 1.9.2 Standard Library Documentation The exception information message set by the last 'raise' (last exception thrown). $@ $ERROR_POSITION Array of the backtrace of the last exception thrown. $& $MATCH The string matched by the last successful pattern match in this scope. $` $PREMATCH The string to the left of the last successful match. $' $POSTMATCH The string to the right of the last successful match. $+ $LAST_PAREN_MATCH The last group of the last successful match. $1 to $9 The Nth group of the last successful regexp match. $~ $LAST_MATCH_INFO The information about the last match in the current scope. $= $IGNORECASE The flag for case insensitive, nil by default (deprecated). $/ $INPUT_RECORD_SEPARATOR, $RS or $-0 The input record separator, newline by default. $\ $OUTPUT_RECORD_SEPARATOR or $ORS The output record separator for the print and IO#write. Default is nil. $, $OUTPUT_FIELD_SEPARATOR or $OFS The output field separator for the print and Array#join. $; $FIELD_SEPARATOR, $FS or $-F The default separator for String#split. $. $INPUT_LINE_NUMBER or $NR The current input line number of the last file that was read. $< $DEFAULT_INPUT 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 The destination of output for Kernel.print and Kernel.printf. The default value is $stdout. $_ $LAST_READ_LINE The last input line of string by gets or readline. $0 Contains the name of the script being executed. May be assignable. $* ARGV Command line arguments given for the script. Also known as ARGV $$ $PROCESS_ID, $PID or Process.pid The process number of the Ruby running this script. $? $CHILD_STATUS 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.
To avoid the criticism that two-character, punctuation-based variable names are cryptic or confusing, part of the standard library is "English" 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.The document on pre-defined global variables and constants from the official Ruby documentation Among the notable ones are:
Global constant name
Description
STDIN
The standard input. The default value for $stdin.
STDOUT
The standard output. The default value for $stdout.
STDERR
The standard error output. The default value for $stderr.
ENV
The hash contains current environment variables.
ARGV
An Array of command line arguments given for the script.
RUBY_VERSION
The Ruby language version, e.g., ruby -e 'puts RUBY_VERSION' will print 2.7.0.
RUBY_RELEASE_DATE
The release date string, e.g., 2019-12-25.
RUBY_PLATFORM
The platform identifier, e.g., x86_64-linux-gnu
RUBY_PATCHLEVEL
The patchlevel for this Ruby, e.g., 0. If this is a development build of Ruby the patchlevel will be -1.
Notes
Ruby Lexicology Literals