File I/O (Input/Output) in Ruby lets you read from and write to files easily and safely. Whether you’re processing logs, saving user data, or generating reports, Ruby’s File and IO classes provide clean and powerful tools.
This tutorial covers Ruby File I/O from the basics to common real-world patterns, with plenty of practical examples.
1) Opening and Closing Files in Ruby
Basic File.open
file = File.open("example.txt", "w")
file.puts "Hello, Ruby!"
file.close
Always close files to free system resources.
2) Using Blocks (Best Practice)
When you open a file with a block, Ruby automatically closes it.
File.open("example.txt", "w") do |file|
file.puts "Hello, Ruby!"
end
This is the recommended approach.
3) Writing to Files
Write (write)
File.open("data.txt", "w") do |file|
file.write("First line\n")
file.write("Second line\n")
end
Append (a mode)
File.open("data.txt", "a") do |file|
file.puts "Appended line"
end
4) Reading Files
Read entire file
content = File.read("data.txt")
puts content
Read line by line
File.foreach("data.txt") do |line|
puts line.chomp
end
Read all lines into an array
lines = File.readlines("data.txt")
p lines
5) File Modes Explained
| Mode | Description | | | – | | "r" | Read only | | "w" | Write (overwrite) | | "a" | Append | | "r+" | Read and write | | "w+" | Read/write (overwrite) | | "a+" | Read/append |
Example:
File.open("file.txt", "r+") do |file|
puts file.read
file.puts "\nNew content"
end
6) Checking File Existence and Info
puts File.exist?("data.txt")
puts File.size("data.txt")
puts File.extname("data.txt")
File metadata
puts File.mtime("data.txt") # last modified time
7) Working with Directories
Create and remove directories
Dir.mkdir("logs") unless Dir.exist?("logs")
Dir.rmdir("logs")
List files in a directory
Dir.entries(".").each do |entry|
puts entry
end
Using glob patterns
Dir.glob("*.txt").each do |file|
puts file
end
8) Handling File Errors with Exceptions
File operations can fail. Always handle exceptions in production code.
begin
content = File.read("missing.txt")
rescue Errno::ENOENT => e
puts "File not found: #{e.message}"
end
9) Reading and Writing JSON Files
require "json"
data = { name: "Alice", age: 30 }
File.open("user.json", "w") do |file|
file.write(JSON.pretty_generate(data))
end
loaded = JSON.parse(File.read("user.json"))
p loaded
10) Streaming Large Files
For large files, avoid loading everything into memory.
File.open("large.log", "r") do |file|
file.each_line do |line|
puts line
end
end
11) Temporary Files
require "tempfile"
Tempfile.create("example") do |file|
file.puts "Temporary data"
puts file.path
end
The file is automatically deleted when closed.
12) Best Practices for Ruby File I/O
- Use block form of
File.open - Handle exceptions (
rescue Errno::ENOENT) - Stream large files line by line
- Use
Tempfilefor temporary data - Avoid hard-coded paths when possible
FAQ
Q: How do I read a file in Ruby? A: Use File.read("file.txt") or File.foreach to read line by line.
Q: How do I write to a file in Ruby? A: Use File.open("file.txt", "w") { |f| f.write("text") }.
Q: How do I append to a file in Ruby? A: Open the file in "a" mode to append content.
