require and require_relative
In this page:
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
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: