rubyguides

How to work with files in Ruby

Ruby provides practical tools for working with files. These recipes keep the common tasks close to the standard library so you can read, write, inspect, and move through paths without extra ceremony. The goal is not to wrap file work in a big abstraction. It is to show the exact calls that solve day-to-day problems cleanly and predictably.

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 cleanly when string concatenation starts to get messy.

The main choice is usually between convenience and control. If you need the whole file, File.read is the quickest option. If the file may be large, File.foreach keeps memory use low and lets you stop early when you find what you need. Path handling is the same kind of tradeoff: plain strings are fine for simple cases, but Pathname gives you safer composition once directories and extensions start changing.

Think of these recipes as the basic toolkit for small scripts and maintenance tasks. The standard library already covers most file work well, so the best improvement is often just choosing the right method and keeping the code easy to scan.

See Also