Requiring Files and Libraries
Prerequisites: Methods
As programs grow, you split them into several files, and you use code that other people have written. Two methods load code from elsewhere.
require_relative — your own files
require_relative loads a file by its path relative to the current
file. Given two files in the same folder:
# greetings.rb
def greet(name)
"Hello, #{name}!"
end
# main.rb
require_relative "greetings"
puts greet("Ada")
$ ruby main.rb
Hello, Ada!
The .rb extension is optional. A file is only loaded once, even if
it's required several times.
require — libraries
require loads a library by name. Ruby ships with a standard
library of useful ones that just need requiring:
require "date"
require "securerandom"
puts Date.new(2025, 1, 15).strftime("%d %B %Y")
puts SecureRandom.hex(4).length
15 January 2025
8
Some everyday standard libraries: json, date, time, set,
fileutils, net/http, securerandom, csv, yaml.
Libraries written by the community are packaged as gems and
installed with the gem or bundle commands. Gems and Bundler are a
Level 2 topic.
Common mistakes
- Using
require "greetings"for your own file.requiresearches Ruby's library paths, not the current folder, and fails withcannot load such file -- greetings (LoadError). Userequire_relative. - Defining methods at the top level of many files. As programs grow, put related methods inside a module or class (Level 2) so names don't clash.
What's next
You now know enough Ruby to build real programs. Try the Beginner Projects, then continue to Level 2 — Intermediate, which starts with classes and objects.