How to Use load in Ruby: Syntax and Examples
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.
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.
# 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
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.
# 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
| Usage | Description |
|---|---|
| load 'file.rb' | Loads and executes the file every time called |
| load 'file.rb', true | Loads file in an anonymous module to isolate namespace |
| require 'file' | Loads file once, ignores extension, caches result |
| load without extension | Raises error, file extension required |
Key Takeaways
load 'filename.rb' to run Ruby code from a file every time you call it.load.true to isolate loaded code and avoid global namespace pollution.load differs from require by reloading the file on each call.