Ruby Predefined Globals

· 10 min read

ruby tips

Below is the summary table for the predefined globals in ruby.

<table class="table table-bordered code"> <tbody> <tr> <td><a href="#bang" class="btn"><strong>$!</strong></a></td> <td><a href="#plus" class="btn"><strong>$+</strong></a></td> <td><a href="#minus-w" class="btn"><strong>$-W</strong></a></td> <td><a href="#minus-v-small" class="btn"><strong>$-v</strong></a></td> <td><a href="#digit" class="btn"><strong>$2</strong></a></td> <td><a href="#digit" class="btn"><strong>$8</strong></a></td> <td><a href="#greater" class="btn"><strong>$&gt;</strong></a></td> </tr> <tr> <td><a href="#double-quotes" class="btn"><strong>$"</strong></a></td> <td><a href="#comma" class="btn"><strong>$,</strong></a></td> <td><a href="#minus-a-small" class="btn"><strong>$-a</strong></a></td> <td><a href="#minus-w-small" class="btn"><strong>$-w</strong></a></td> <td><a href="#digit" class="btn"><strong>$3</strong></a></td> <td><a href="#digit" class="btn"><strong>$9</strong></a></td> <td><a href="#qmark" class="btn"><strong>$?</strong></a></td> </tr> <tr> <td><a href="#dollar" class="btn"><strong>$$</strong></a></td> <td><a href="#minus-zero" class="btn"><strong>$-0</strong></a></td> <td><a href="#minus-d-small" class="btn"><strong>$-d</strong></a></td> <td><a href="#dot" class="btn"><strong>$.</strong></a></td> <td><a href="#digit" class="btn"><strong>$4</strong></a></td> <td><a href="#colon" class="btn"><strong>$:</strong></a></td> <td><a href="#at" class="btn"><strong>$ @ </tr> <tr> <td><a href="#ampersand" class="btn"><strong>$&amp;</strong></a></td> <td><a href="#minus-f" class="btn"><strong>$-F</strong></a></td> <td><a href="#minus-i-small" class="btn"><strong>$-i</strong></a></td> <td><a href="#slash" class="btn"><strong>$/</strong></a></td> <td><a href="#digit" class="btn"><strong>$5</strong></a></td> <td><a href="#semicolon" class="btn"><strong>$;</strong></a></td> <td><a href="#backslash" class="btn"><strong>$</a></td> </tr> <tr> <td><a href="#end-quote" class="btn"><strong>$'</strong></a></td> <td><a href="#minus-i" class="btn"><strong>$-I</strong></a></td> <td><a href="#minus-l-small" class="btn"><strong>$-l</strong></a></td> <td><a href="#digit" class="btn"><strong>$0</strong></a></td> <td><a href="#digit" class="btn"><strong>$6</strong></a></td> <td><a href="#less" class="btn"><strong>$&lt;</strong></a></td> <td><a href="#underscore" class="btn"><strong>$ </strong></a></td> </tr> <tr> <td><a href="#splat" class="btn"><strong>$ </strong></a></td> <td><a href="#minus-k" class="btn"><strong>$-K</strong></a></td> <td><a href="#minus-p-small" class="btn"><strong>$-p</strong></a></td> <td><a href="#digit" class="btn"><strong>$1</strong></a></td> <td><a href="#digit" class="btn"><strong>$7</strong></a></td> <td><a href="#tilde" class="btn"><strong>$ </strong></a></td> <td><a href="#backtick" class="btn"><strong>$

VariableDescription
$! Exception === $! unless $!.nil?

read-only thread-local  The last exception, that was thrown and rescued in the current context.
Locals to the rescue clause.

ruby > 0 / 0 rescue $! # ⇒ > begin > 0 / 0 > rescue > $! > end # ⇒ > 0 / 0 # ZeroDivisionError: divided by 0 # from (pry):67:in `/' > $! # ⇒ nil
$" Array === $"

read-only  Array of strings, containing absolute paths to loaded files.
Files, loaded within both Kernel’s load, require, require_relative directives and platform-specific DL/Fiddle, are shown in the list.

ruby > $" # ⇒ [ # [ 0] "enumerator.so", # [ 1] "/…/lib/ruby/2.0.0/x86_64-linux/enc/encdb.so", # [ 2] "/…/lib/ruby/2.0.0/x86_64-linux/enc/trans/transdb.so", # [ 3] "/…/lib/ruby/site_ruby/2.0.0/rubygems/defaults.rb", # [ 4] "/…/lib/ruby/2.0.0/x86_64-linux/rbconfig.rb", # … # [227] "/…/lib/ruby/2.0.0/dl.rb" # ]
$$ Fixnum === $$

read-only  Current process ID.

ruby > $" # ⇒ 8603 > Process.pid # ⇒ 8603
$& String === $& unless $&.nil?

read-only thread-local  The matched string from the previous successful pattern match.
Locals to the pattern match scope.

ruby > "foo bar baz".match /foo|bar|baz/ # ⇒ > $& # ⇒ "foo" > "foo bar baz".gsub /foo|bar|baz/, "ggg" # ⇒ "ggg ggg ggg" > $& # ⇒ "baz" > "foo bar baz".match /foobarbaz/ # ⇒ nil > $& # ⇒ nil
$' String === $' unless $'.nil?

read-only thread-local  The rest of the string after the matched substring in the previous successful pattern match.
Locals to the pattern match scope.

ruby > "foo bar baz".match /foo|bar|baz/ # ⇒ > $' # ⇒ " bar baz" > "foo bar baz".gsub /foo|bar|baz/, 'ggg' # ⇒ "ggg ggg ggg" > $' # ⇒ "" > "foo bar baz".match /foobarbaz/ # ⇒ nil > $' # ⇒ nil
$* Array === $*

read-only  The command line arguments passed to the currently executed ruby script.
An alias for ARGV.

ruby ~ pry --simple-prompt > $* # ⇒ [ # [0] "--simple-prompt" # ] > ARGV # ⇒ [ # [0] "--simple-prompt" # ]
$+ String === $+ unless $+.nil?

read-only thread-local  The last captured match from the previous successful pattern match.
Locals to the pattern match scope. Contains nil if there was no capture (even while match was successful.)

ruby > "foo bar baz".match /(foo) (bar) baz/ # ⇒ > $+ # ⇒ "bar" > "foo bar baz".scan (/a(\S)/) { |m| puts m } # r # z # ⇒ "foo bar baz" > $+ # ⇒ "z" > "foo bar baz".match /foo bar baz/ # ⇒ > $+ # ⇒ nil
$, String === $, unless $,.nil?

read-write  Separator for both Kernel#print and Array#join.
Defaults to nil.

ruby > print "foo", "bar", "baz" # foobarbaz⇒ nil > %w[foo bar baz].join # ⇒ "foobarbaz" > $,='%' # ⇒ "%" > print "foo", "bar", "baz" # foo%bar%baz⇒ nil > %w[foo bar baz].join # ⇒ "foo%bar%baz"
$-0

$/ String === $-0 unless $-0.nil?
String === $/ unless $/.nil?

read-write  Input record separator.
Defaults to \n. May be set with the -0 command line parameter (as octal value.)

ruby > $-0='%' # ⇒ "%" > gets f o o % # ⇒ "f\no\no\n%" ~ ruby -045 /…/bin/pry > gets f o o % # ⇒ "f\no\no\n%" >
$-F

$; String === $-F unless $-F.nil?
String === $: unless $:.nil?

read-write  Default field separator for String#split.
Defaults to nil. May be set with the -F command line parameter.

ruby > $-F # ⇒ nil > "foo bar baz".split # ⇒ [ # [0] "foo", # [1] "bar", # [2] "baz" # ] > $-F='%' # ⇒ "%" > "foo bar baz".split # ⇒ [ # [0] "foo bar baz" # ] > "foo%bar%baz".split # ⇒ [ # [0] "foo", # [1] "bar", # [2] "baz" # ] > $-F == $; # ⇒ true
$-I

$: Array === $-I
Array === $:

read-only  Array of include paths.
Absolute paths to be searched by Kernel.load and/or Kernel.require.

ruby > $-I # ⇒ [ # [ 0] "/…/gems/rubygems-bundler-1.1.0/lib", # [ 1] "/…/gems/bundler-1.2.3/lib", # [ 2] "/…/gems/coderay-1.0.8/lib", # [ 3] "/…/gems/slop-3.4.3/lib", # … # [14] "/…/lib/ruby/2.0.0/x86_64-linux" # ] > $-I == $: # ⇒ true
$-K String === $-K unless $-K.nil?

obsolete read-write  Determines the encoding to be used whilst parsing .rb files.
One should avoid using that variable since ruby-1.9.

ruby > $-K # (pry):13: warning: variable $KCODE is no longer effective # ⇒ nil
$-W Fixnum === $-W

read-only  Current verbosity level.
Defaults to 1. May be set to 0 with the -W0 command line arg and to 2 with one of -w, -v, or --verbose switches.

ruby > $-W # ⇒ 1 > exit ~ ruby -v /…/bin/pry # ruby 2.0.0dev (2012-12-01 trunk 38126) [x86_64-linux] # /…/gems/method_source-0.8.1/lib/method_source/code_helpers.rb:38: warning: assigned but unused variable - e2 # … # /…/gems/pry-0.9.11.4/lib/pry/pry_class.rb:446: warning: instance variable @critical_section not initialized > $-W # /…/gems/awesome_print-1.1.0/lib/awesome_print/inspector.rb:114: warning: instance variable @force_colors not initialized # ⇒ 2 > exit ~ ruby -W0 /…/bin/pry > $-W # ⇒ 0 >
$-a ∈ [true, false]

read-only  Denotes whether the auto-split mode was enabled with -a command line argument.
-a switch makes sense when used together with either -p or -n args. In auto-split mode, Ruby executes $F = $_.split at the beginning of each loop.

ruby ~ cat > test-a-switch.rb 〈〈EOF # heredoc> # encoding: utf-8 # heredoc> puts "LINE=[#{\$_.strip}]" # heredoc> puts "\$F=#{\$F}" # heredoc> EOF ~ ruby -a -n test-a-switch.rb test-a-switch.rb # LINE=[# encoding: utf-8] # $F=["#", "encoding:", "utf-8"] # LINE=[puts "LINE=#{$_.strip}"] # $F=["puts", "\"LINE=\#{$_.strip},"] # LINE=[puts "$F=#{$F}"] # $F=["puts", "$F=\#{$F}\""] ~ ruby -n test-a-switch.rb test-a-switch.rb # LINE=# encoding: utf-8 # $F= # LINE=puts "LINE=#{$_.strip}" # $F= # LINE=puts "$F=#{$F}" # $F=
$-d ∈ [true, false]

read-only  Denotes whether the debug mode was enabled with -d switch.

ruby ~ cat > test-d-switch.rb 〈〈EOF # heredoc> puts "DEBUG MODE: #{\$-d}" # heredoc> EOF ~ ruby -d test-d-switch.rb # Exception `LoadError' at /…/lib/ruby/site_ruby/2.0.0/rubygems.rb:1264 - cannot load such file -- rubygems/defaults/operating_system # Exception `LoadError' at /…/lib/ruby/site_ruby/2.0.0/rubygems.rb:1273 - cannot load such file -- rubygems/defaults/ruby # DEBUG MODE: true
$-i ∈ [true, false]

read-only  Value of the -i command line argument, if given.
Defaults to nil. When provided, this argument enables inplace-edit mode; the parameter specifies an extension of backup file to be created.

ruby ~ cat > test-i-switch.rb << EOF \$_.upcase! puts "i-switch: #{\$-i}" EOF ~ ruby -p -i.bak test-i-switch.rb test-i-switch.rb ~ cat test-i-switch.rb # i-switch: .bak # $_.UPCASE! # i-switch: .bak # PUTS "I-SWITCH: #{$-I}"
$-l ∈ [true, false]

read-only  Denotes whether the automatic line-ending processing mode was enabled with -l switch.
Automatic line-endings sets $\ to the value of $/, and (when used with either -p or -n args) chops every line read using chop!.

ruby # Could not invent a meaningful example :-(
$-p ∈ [true, false]

read-only  Denotes whether the “gets loop around” mode was enabled with -p switch.
-p switch acts mostly like -n sibling with one exception: it prints the value of variable $_ at the each end of the loop.
For some unknown reason there is no internal global to get aknowledged whether the -n command line switch was given. In case it were, Ruby is to assume the following loop around your script, which provides an iteration over filename arguments somewhat like sed -n and awk do.

ruby while gets … end

An example of usage follows:

ruby ~ echo "foo bar baz" | ruby -p -e '$_.tr! "o-z", "O-Z"' # ⇒ fOO baR baZ
$-v

$-w ∈ [true, false]

read-only  Denotes whether the verbose mode was enabled with either -v or -w switch.

ruby ~ cat > test-v-switch.rb 〈〈EOF # heredoc> puts "VERBOSE MODE: #{\$-v}" # heredoc> EOF ~ ruby -v test-v-switch.rb # ruby 2.0.0dev (2012-12-01 trunk 38126) [x86_64-linux] # VERBOSE MODE: true ~
$. Fixnum === $.

read-only  Number of the last line read from the current input file ARGF.
ARGF is a stream designed to use in scripts that process files given as command-line arguments or passed in via STDIN.

ruby ARGV.replace ["file1"] # file1 ≡ 'a\nb\nc\nd' ARGF.readlines # Returns the contents of file1 as an Array $. # ⇒ 4
$0…$9 String === $0 unless $0.nil?
String === $1 unless $1.nil?
String === $2 unless $2.nil?
String === $3 unless $3.nil?
String === $4 unless $4.nil?
String === $5 unless $5.nil?
String === $6 unless $6.nil?
String === $7 unless $7.nil?
String === $8 unless $8.nil?
String === $9 unless $9.nil?

read-only  The N-th capture of the previous successful pattern match.
Defaults to nil if the match failed or if N is greater than an amount of captured groups.

ruby > "foo bar baz".match(/(foo) (bar)/) # ⇒ > $1 # ⇒ "foo" > $2 # ⇒ "bar" > $3 # ⇒ nil
$< ARGF === $<

read-only  Read‐only alias for ARGF.

ruby > $<.class # ⇒ ARGF.class < Object
$= ∈ [true, false]

obsolete  

ruby > $= # (pry):23: warning: variable $= is no longer effective # ⇒ false
$> IO === $>

read-write  Standard output stream.

ruby > $> = File.new('/tmp/foo', 'w') # ⇒ # -rw-r--r-- 1 am users 0 Feb 27 12:41 /tmp/foo > puts "bar baz" # ⇒ nil > exit ~ cat /tmp/foo # bar baz
$? Process::Status === $? unless $?.nil?

read-only  Exit status of the last terminated process within current context.

ruby > `ls FooBarBaz` # ls: невозможно получить доступ к FooBarBaz: Нет такого файла или каталога # ⇒ "" > $? # ⇒
$@ Array === $@ unless $@.nil?

read-only thread-local  Shorthand to $!.backtrace
Locals to the rescue clause.

ruby > 0 / 0 rescue $@ # ⇒ [ # [ 0] "(pry):7:in `/'", # [ 1] "(pry):7:in `__pry__'", # … # [23] "/…/bin/ruby_noexec_wrapper:14:in `
'" # ]
$\ String === $\ unless $\.nil?

read-write  Appended to Kernel.print output.
Defaults to nil, or to $/ if the -l switch was given.

ruby > $\='%' # ⇒ "%" > print 'foo', 'bar', 'baz' # ⇒ %foobarbaz%=> nil
$_ String === $_ unless $_.nil?

read-only thread-local  Last String read from IO by one of Kernel.gets, Kernel.readline or siblings.
Widely used with -p and -n switches.

ruby > gets foo # ⇒ "foo\n" > $_ # ⇒ "foo\n"
$ </strong></code> <span class="code">String === $ unless $ .nil?</span> </td> <td> <p><span class="label label-important">read-only</span> <span class="label label-info">thread-local</span>  <strong>The rest of the string <em>before</em> the matched substring in the previous successful pattern match.</strong><br> Locals to the pattern match scope.</p>
> "foo bar baz".match /bar|baz/
# ⇒ <MatchData "bar">
> $`
# ⇒ "foo "

> "foo bar baz".gsub /foo|bar|baz/, 'ggg'
# ⇒ "ggg ggg ggg"
> $`
# ⇒ "foo bar "

> "foo bar baz".match /foobarbaz/
# ⇒ nil
> $`
# ⇒ nil

</td> </tr> <tr> <td class="tooltipable"> <a id="tilde"></a> <code class="btn btn-large disabled"><strong>$ </strong></code> <span class="code">MatchData === $ unless $ .nil?</span> </td> <td> <p><span class="label label-important">read-only</span> <span class="label label-info">thread-local</span>  <strong>The <code>MatchData</code> from the previous successful pattern match.</strong><br></p>

> "abc12def34ghijklmno567pqrs".gsub (/\d+/) { |m| p $~ }
# ⇒ <MatchData "12">
# ⇒ <MatchData "34">
# ⇒ <MatchData "567">

</td> </tr> </tbody> </table> </div>

Credits to Jim Neath and runpaint , some examples came from these posts.