0
0
RubyHow-ToBeginner · 3 min read

How to Use require in Ruby: Syntax and Examples

In Ruby, require is used to load external files or libraries so you can use their code in your program. You write require 'filename' to include a file or gem, and Ruby loads it once during runtime.
📐

Syntax

The require method loads an external Ruby file or library into your current program. You provide the file name or library name as a string without the .rb extension.

  • require 'filename': Loads the file or library named filename.rb or a gem.
  • Ruby searches in the load path for the file.
  • The file is loaded only once, even if require is called multiple times.
ruby
require 'json'
require 'my_library'
💻

Example

This example shows how to use require to load Ruby's built-in JSON library and parse a JSON string.

ruby
require 'json'

json_string = '{"name": "Alice", "age": 30}'
parsed = JSON.parse(json_string)
puts "Name: #{parsed['name']}"
puts "Age: #{parsed['age']}"
Output
Name: Alice Age: 30
⚠️

Common Pitfalls

Common mistakes when using require include:

  • Forgetting that require loads files only once, so changes in required files won't reload automatically.
  • Using relative paths incorrectly; require searches the load path, not relative to the current file.
  • Confusing require with load, which reloads files every time.
ruby
## Wrong: Using relative path with require (may fail)
# require './my_script'

## Right: Use require_relative for relative paths
require_relative 'my_script'
📊

Quick Reference

UsageDescription
require 'library_name'Load a library or gem once
require 'file_name'Load a Ruby file from load path once
require_relative 'file_name'Load a Ruby file relative to current file
load 'file_name.rb'Reload a Ruby file every time it is called

Key Takeaways

require loads external Ruby files or libraries once during program execution.
Use require with library or file names without extensions, relying on Ruby's load path.
For relative file loading, prefer require_relative instead of require.
require does not reload files if called multiple times; use load to reload.
Common errors include incorrect paths and misunderstanding when files are loaded.