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

require and require_relative

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
🔒

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.