0
0
RubyHow-ToBeginner · 3 min read

How to Use load in Ruby: Syntax and Examples

In Ruby, load is used to read and execute Ruby code from an external file every time it is called. You use it by passing the file path as a string to load, like load 'filename.rb', which runs the code in that file immediately.
📐

Syntax

The load method takes a string argument specifying the path to a Ruby file. It reads and executes the code in that file each time load is called. You can optionally pass true as a second argument to wrap the loaded code in an anonymous module, avoiding polluting the global namespace.

  • load 'file.rb': Loads and runs the file every time.
  • load 'file.rb', true: Loads the file in an isolated namespace.
ruby
load(filename, wrap = false)
💻

Example

This example shows how load runs code from an external file each time it is called, reflecting any changes made to that file without restarting the program.

ruby
# file: greeting.rb
puts 'Hello from the loaded file!'

# main.rb
3.times do |i|
  puts "Load attempt #{i + 1}:"
  load 'greeting.rb'
  sleep 1
end
Output
Load attempt 1: Hello from the loaded file! Load attempt 2: Hello from the loaded file! Load attempt 3: Hello from the loaded file!
⚠️

Common Pitfalls

One common mistake is confusing load with require. Unlike require, load runs the file every time it is called, which can cause unexpected repeated execution. Also, load needs the exact file path and extension, while require can omit the extension. Forgetting to use the full path or the correct file extension can cause errors.

Another pitfall is not using the optional wrap argument when you want to avoid polluting the global namespace with loaded code.

ruby
# Wrong: forgetting file extension
# load 'greeting'  # This will raise an error

# Right: include file extension
load 'greeting.rb'

# Using wrap to avoid global namespace pollution
load 'greeting.rb', true
📊

Quick Reference

UsageDescription
load 'file.rb'Loads and executes the file every time called
load 'file.rb', trueLoads file in an anonymous module to isolate namespace
require 'file'Loads file once, ignores extension, caches result
load without extensionRaises error, file extension required

Key Takeaways

Use load 'filename.rb' to run Ruby code from a file every time you call it.
Always include the file extension when using load.
Use the optional second argument true to isolate loaded code and avoid global namespace pollution.
Remember that load differs from require by reloading the file on each call.
Check file paths carefully to avoid load errors.