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.
In this page:
Syntax
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
require "json"
data = { name: "Alice", age: 30 }
json_text = data.to_json
puts json_text
puts JSON.parse(json_text).inspect
Login to try C/C++/Java/PHP code in the editor
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
- Using
require "./helper"with a relative path in a different working directory, whenrequire_relative "helper"is safer. - Forgetting to
require "json"before callingto_jsonorJSON.parse, which raisesNoMethodErrororNameError. - Requiring the same file many times and expecting it to reload, when
requireloads a file only once.
Chapter Summary
- Modules group methods and constants, and
includeandextendmix them into classes. ComparableandEnumerableadd comparison and collection behavior.- Namespacing,
require, andrequire_relativeorganize and load code.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: