Assign `$gvar` at the top level, then read it inside a method defined in a class: the method can still see the value. Replace `$gvar` with a top-level local variable, and that access no longer works. The difference is scope, not the object currently acting as `self`. section 5.2.1 section 5.2
$gvar = "I'm a global!"
class C
def examine_global
puts $gvar
end
end
c = C.new
c.examine_global #1
The listing shows a top-level global read from a method inside a class. section 5.2.1
A leading dollar sign identifies a Ruby global variable. Unlike a local variable, an initialized global remains accessible across class and method definitions and changes of `self`. Names need not resemble ordinary variable names: `$population`, `$1`, `$:`, and `$/` are all globals. Uppercase after the dollar sign is a naming convention, not a requirement. section 1.1.3 section 5.2.1
Some globals are supplied by Ruby:
- `$0` holds the startup file name; `$:` holds the library load path and is also available as `$LOAD_PATH`; `$$` holds the Ruby process ID. `require "English"` makes friendlier names available for some built-in globals. section 5.2.1
- A successful regular-expression match populates `$1`, `$2`, and so on with parenthesized captures, and sets `$~` to a `MatchData` object. An unsuccessful match sets `$~` to `nil`. A returned `MatchData` object offers a more structured way to retrieve captures. section 11.4.1 section 11.4.4
- After `system` runs a program, `$?` holds a `Process::Status` object with its process ID and exit status. section 14.6.1
“Global” has a threading qualification. An ordinary global such as a user-created `$var` can be changed by another thread, but numbered regexp captures are thread-local: one thread’s `$1` does not replace another’s. `$?` is thread-local too. To inspect names currently defined, call `global_variables`; it returns an array of symbols, not their values, and includes thread-local globals. section 14.5.4 section 15.3.1 section 14.6.1











