ruby.onl / one-liners

Ruby's Special Variables: The $ Survivors' Club

2026-03-13

Ruby inherited most of Perl's special variables, and they work exactly how you'd expect. If you've spent years training your fingers to type $_ and $. and $1, congratulations. That muscle memory transfers directly.

Part 1: Input/Output Variables

$ (Current line)

The default variable for -n and -p loops. Exactly like Perl's $_.
# With -n switch, $_ holds current line ruby -ne 'puts $_ if /ERROR/'

$F (Split fields)

Array of fields when using -a (auto-split). Like Perl's @F.
# Print third field of each line ruby -ane 'puts $F[2]'
In Perl it's @F (array sigil). In Ruby it's $F (still a global, but Ruby arrays don't need sigils).

$. (Line number)

Current line number of the last file read. Identical to Perl's $..
# Print line numbers ruby -ne 'printf "%4d: %s", $., $_'

$/ (Input record separator)

Controls what Ruby considers a "line". Default is "\n". Like Perl's $/.
# Read paragraph mode (blank-line separated) $/ = "\n\n" ARGF.each { |para| puts para.length } # Slurp entire file $/ = nil entire_file = ARGF.read

$\ (Output record separator)

Appended after every print. Default is nil. Like Perl's $\.
# Auto-add newline to every print $\ = "\n" print "no need for puts" # newline added automatically

$; (Default split separator)

Default separator for String#split. Like Perl's unset $/ affecting split.
$; = "," "a,b,c".split # => ["a", "b", "c"]

Part 2: Regex Match Variables

$& (Last match)

The string matched by the last regex. Like Perl's $&.
"hello123world" =~ /\d+/ puts $& # => "123"

$1, $2, $3... (Capture groups)

Captured groups from the last regex match. Identical to Perl.
"2024-01-15" =~ %r~(\d{4})-(\d{2})-(\d{2})~ puts $1 # => "2024" puts $2 # => "01" puts $3 # => "15"

$~ (MatchData)

The MatchData object from the last regex match. No direct Perl equivalent.
"hello123" =~ /(\d+)/ puts $~[0] # => "123" (full match) puts $~[1] # => "123" (first capture)

$ and $' (Pre-match and Post-match)

String before and after the last match. Like Perl's <<::IC::>>0<<::IC::>> and $'.

Part 3: Process and File Variables

$0 and $PROGRAM_NAME

Name of the current script. Like Perl's
$0.
puts "Running: #{$0}"

$$ and $PID

Current process ID. Like Perl's
$$.

$? and $CHILD_STATUS

Exit status of last child process. Like Perl's
$?.
system("ls /nonexistent") puts $?.exitstatus # => non-zero

$FILENAME

Current filename being read by ARGF. Like Perl's
$ARGV.
ruby -ne 'puts "#{$FILENAME}:#{$.}: #{$_}"' *.log

$stdin, $stdout, $stderr

The standard IO streams. Like Perl's
STDIN, STDOUT, STDERR.
$stderr.puts "Warning: something happened"

Part 4: The Useful Globals

Part 5: Perl Variables That Don't Exist in Ruby

The good news is you already know 90% of these. The bad news is the 10% you don't know will bite you exactly once each, and then you'll never forget.


Created By: Wildcard Wizard. Copyright 2026