require vs require_relative in Ruby

Ruby 2 min read
Short answer

require searches the load path and is for gems and standard library. require_relative resolves against the directory of the current file and is for your own project files.

ruby
require 'json'                    # standard library
require 'nokogiri'                # a gem
require_relative 'lib/parser'     # a file in your project

#Why the distinction matters

require with a relative path used to resolve against the working directory, which changes depending on where the program was launched from. Running ruby bin/app.rb from the project root and from inside bin/ would behave differently.

require_relative resolves against the file doing the requiring, so it works no matter where the process was started.

#Extensions are optional

require_relative 'parser' finds parser.rb. Include the extension only for non-.rb files.

#Both load exactly once

Requiring the same file twice is a no-op. This is why redefining a constant does not warn on the second require — the second require never happened.

load re-executes every time, which is occasionally useful in a console and almost never otherwise.

#In a gem or Rails app

You mostly stop writing either one. Bundler handles gems from your Gemfile, and Rails autoloads app/ by naming convention — app/models/video.rb defines Video and is loaded on first reference.

#Load errors

text
LoadError: cannot load such file -- nokogiri

Either the gem is not installed (bundle install), or you are running outside the bundle (bundle exec ruby app.rb), or the path in require_relative is wrong.