liveBook · Manning

Load

As explained in The Well-Grounded Rubyist, Fourth Edition

A Ruby method that locates and evaluates a source file each time it is invoked, using the load path unless given an explicit path.

Ruby's load method reads and evaluates another source file when execution reaches the call. It helps split large programs into separate files and returns to the caller afterward. section 1.3.1

puts "This is the first (master) program file."
load "loadee.rb"
puts "And back again to the first file."

A two-file trace makes load's execution order concrete: Ruby runs the first file, evaluates the loaded file, then resumes the first file. section 1.3.1

Use load with these path and execution rules:

  • Find a filename in the load path, searched in order; treat the current directory as a special case even though . is not listed there. section 1.3.2
  • Navigate relative to the current directory with paths such as ../extras.rb; changing directories during execution changes how those references resolve. section 1.3.2
  • Bypass the load path with a fully qualified filename. section 1.3.2
  • Evaluate the file every time the call runs, allowing updated definitions to override earlier ones during an interactive session. section 1.3.2
  • Compute the filename dynamically or place the call inside a conditional because load is an ordinary method executed at that point. section 1.3.2

A file that loads another file

With load_demo.rb calling load "loadee.rb", Ruby prints the first file's message, evaluates loadee.rb, prints its message, and then resumes load_demo.rb. Prefer require for ordinary library loading when repeated calls should not reload the feature; choose load when deliberate re-evaluation is useful. section 1.3.1 section 1.3.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains ordered path lookup, explicit paths, execution timing, conditional calls, and repeated evaluation, but not extension internals.
Examples
Demonstrates load_demo.rb, loadee.rb, relative paths, absolute paths, and inspecting $LOAD_PATH.
What it assumes
Assumes basic Ruby files and execution while teaching load paths, relative paths, and runtime method evaluation.
What you can do after
Apply it to split programs, select files conditionally, and reload modified definitions during an irb session.
How it connects
Contrasts load with require and connects both to the load path, libraries, extensions, and runtime file evaluation.

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.