liveBook · Manning

Built-in global variable

As explained in The Well-Grounded Rubyist, Fourth Edition

A built-in global variable is a Ruby global variable initialized by the interpreter when Ruby starts.

Ruby initializes built-in global variables when the interpreter starts. They remain available across scope changes, including inside methods defined within classes. section 5.2.1

Common built-in globals expose runtime and loading information:

  • $0 contains the startup file name, $: contains directories Ruby searches when loading external files, and $$ contains the Ruby process ID. section 5.2.1
  • Use require "English" for friendlier aliases such as $INPUT_LINE_NUMBER for $. and $PID for $$; $LOAD_PATH is available without requiring it. section 5.2.1
$gvar = "I'm a global!"
class C
  def examine_global
    puts $gvar
  end
end
c = C.new
c.examine_global        #1

Trace how a global value remains accessible inside a method after class-definition scope changes. section 5.2.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains initialization, cross-scope availability, representative values, and readable aliases, but defers the complete variable set.
Examples
Uses $0, $:, $$, English.rb aliases, and a cross-scope $gvar example.
What you can do after
Evaluate/understand Ruby’s predefined global values and select friendlier aliases through English.rb.
How it connects
Connects built-in global variables with global scope, loading external files, require, and thread-local globals.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.