← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 6 of 6

require and require_relative

require brings in code from a library, and require_relative brings in a file next to yours. It is like borrowing a book from the public library versus from your own shelf.
Syntax
ruby
require "library"
require_relative "path/to/file"

require and require_relative

require "library" loads code from Ruby's standard library or an installed gem, while require_relative "./file" loads a file relative to the current file's location, commonly used for your own project's files.

Both only load a given file once, even if required multiple times, avoiding duplicate definitions. This is Ruby's mechanism for splitting code across multiple files and reusing external libraries.

Note: Use require_relative for your own project files and require for standard library or installed gems.

Example: require and require_relative

markup
require "json"

data = { name: "Alice", age: 30 }
json_text = data.to_json

puts json_text
puts JSON.parse(json_text).inspect
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using require "./helper" with a relative path in a different working directory, when require_relative "helper" is safer.
  2. Forgetting to require "json" before calling to_json or JSON.parse, which raises NoMethodError or NameError.
  3. Requiring the same file many times and expecting it to reload, when require loads a file only once.
Chapter Summary
  • Modules group methods and constants, and include and extend mix them into classes.
  • Comparable and Enumerable add comparison and collection behavior.
  • Namespacing, require, and require_relative organize and load code.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.