How to Work with Files in Ruby
· 2 min read · Updated March 19, 2026 · beginner
ruby file io cookbook
Ruby provides robust tools for working with files. Here are practical recipes for everyday file operations.
Reading Files
Problem
You need to read file contents efficiently.
Solution
# Read entire file into string
content = File.read("config.txt")
# Read into array of lines
lines = File.readlines("log.txt")
# Process line by line (memory efficient)
File.foreach("large_log.txt") do |line|
puts line if line.include?("ERROR")
end
# With block ensures file closes automatically
File.open("input.txt", "r") do |file|
file.each_line { |line| process(line) }
end
Writing Files
Problem
You need to write content to a file.
Solution
# Overwrite file
File.write("output.txt", "Hello, world!")
# Append to file
File.open("log.txt", "a") do |file|
file.puts "#{Time.now} - Log entry"
end
File Information
Problem
You need to check if a file exists or get its metadata.
Solution
File.exist?("config.yml") # => true/false
File.file?("data.txt") # => true if regular file
File.directory?("logs/") # => true if directory
File.size("data.bin") # => size in bytes
File.mtime("script.rb") # => modification time
Paths
Problem
You need to manipulate file paths safely across platforms.
Solution
require "pathname"
base = Pathname.new("/home/user/project")
config = base + "config" + "settings.yml"
config.dirname # directory path
config.basename # filename
config.extname # extension like .yml
config.exist? # true/false
Summary
Use File.read and File.write for simple tasks. Process large files line by line with File.foreach. Pathname handles complex path operations reliably.
See Also
- Ruby Tempfile and Tmpdir — Creating temporary files and directories safely
- Ruby String Methods — Reading and writing file contents involves string manipulation
- Ruby Core Classes — File and IO are foundational built-in classes for file operations