Predefined Variables

Table 3 lists all of Ruby’s predefined variables.

Table 3. Predefined variables

Predefined variable

Description

$!

The exception information message containing the last exception raised. raise sets this variable. Access with => in a rescue clause.

$@

The stack backtrace of the last exception, retrievable via Exception#backtrace.

$&

The string matched by the last successful pattern match in this scope, or nil if the last pattern match failed. Same as m[0] where m is a MatchData object. Read only. Local.

$'

String preceding whatever was matched by the last successful pattern match in the current scope, or nil if the last pattern match failed. Same as m.pre_match where m is a MatchData object. Read only. Local.

$'

String following whatever was matched by the last successful pattern match in the current scope, or nil if the last pattern match failed. Same as m.post_match where m is a MatchData object. Read only. Local.

$+

Last bracket matched by the last successful search pattern, or nil if the last pattern match failed. Useful if you don’t know which of a set of alternative patterns matched. Read only. Local.

$1, $2 . . .

Subpattern from the corresponding set of parentheses in the last successful pattern matched, not counting patterns matched in nested blocks that have been exited already, or nil if the last pattern match failed. Same as m[n] where m is a MatchData object. Read only. Local.

Information about the last match in the current scope. Regex#match returns the last match ...

Get Ruby Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.