Ruby provides simple, elegant, and powerful ways to read from and write to files. The language emphasizes readability and developer happiness, making file I/O operations straightforward. This guide covers the most common and idiomatic approaches with practical examples.
Basic Concepts
In Ruby, file operations are typically performed using the File class or the shorter File.open method. Most file operations use ブロック to ensure files are properly closed after use, preventing resource leaks.
Opening a File
The recommended way is to use a block form:
ruby
File.open("filename.txt", "r") do |file|
# work with the file
終わり
# file is automatically closed hereWithout a block, you must manually close the file:
ruby
file = File.open("filename.txt", "r")
# ... operations ...
file.closeFile Modes
The second argument to File.open is the mode string:
| Mode | Meaning |
| “r” | Read-only (default) |
| “w” | Write-only, creates/truncates file |
| “a” | Write-only, appends to file |
| “r+” | Read and write, preserves content |
| “w+” | Read and write, truncates file |
| “a+” | Read and write, appends |
Add “b” for binary mode on Windows (e.g., “rb”, “wb”).
Reading Files in Ruby
1. Read Entire File as a String
ruby
content = File.read("example.txt")
puts contentOr using File.open:
ruby
content = File.open("example.txt", "r") { |f| f.read }2. Read Entire File into an Array of Lines
ruby
lines = File.readlines("example.txt")
lines.each { |line| puts line }
# Or more idiomatically:
File.readlines("example.txt").each do |line|
puts "Line: #{line.chomp}"
end3. Read Line by Line (Most Memory-Efficient)
Ideal for large files:
ruby
File.open("large_file.txt", "r") do |file|
file.each_line do |line|
puts line.chomp.upcase
end
endOr using the shorter foreach:
ruby
File.foreach("large_file.txt") do |line|
process(line.chomp)
end4. Read Specific Number of Bytes or Lines
ruby
File.open("data.bin", "rb") do |f|
header = f.read(16) # read first 16 bytes
puts header
end
# Read first 5 lines
first_five = File.foreach("log.txt").first(5)5. Read with Encoding Specified
ruby
content = File.read("utf8_file.txt", encoding: "UTF-8")
# or
File.open("file.txt", "r:UTF-8") do |f|
f.each_line { |line| puts line }
endWriting Files in Ruby
1. Write a String to a File (Overwrites)
ruby
File.write("output.txt", "Hello, Ruby!\nThis is a new file.")This is the simplest and most common way.
2. Write Using File.open (Block Form)
ruby
File.open("greeting.txt", "w") do |file|
file.puts "Hello World"
file.puts "Welcome to Ruby file I/O"
file.write "This line is written without newline"
file << " << This uses the shovel operator\n"
endMethods available inside the block:
puts– adds newlineprint– no newlinewrite– no newline (alias for<<)<<– shovel operator
3. Append to a File
ruby
File.open("log.txt", "a") do |file|
file.puts "#{Time.now}: Application started"
end
# Or shorter:
File.write("log.txt", "New log entry\n", mode: "a")4. Write Array of Lines
ruby
lines = ["First line", "Second line", "Third line"]
File.open("lines.txt", "w") do |file|
lines.each { |line| file.puts line }
end
# Or even shorter:
File.write("lines.txt", lines.join("\n") + "\n")Practical Examples
Example 1: Copy a File
ruby
def copy_file(source, destination)
File.write(destination, File.read(source))
end
copy_file("source.txt", "backup.txt")Or in binary mode:
ruby
File.write("backup.bin", File.read("original.bin", mode: "rb"), mode: "wb")Example 2: Simple CSV Writer
ruby
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "London"]
]
File.open("people.csv", "w") do |file|
data.each do |row|
file.puts row.join(",")
end
endExample 3: Simple CSV Reader
ruby
File.foreach("people.csv") do |line|
name, age, city = line.chomp.split(",")
puts "#{name} is #{age} years old and lives in #{city}"
endExample 4: Count Lines in a File
ruby
line_count = File.foreach("large.txt").inject(0) { |count, _| count + 1 }
puts "Total lines: #{line_count}"
# Or more simply (loads all lines into memory):
puts File.readlines("file.txt").sizeExample 5: Safe File Writing (Atomic Write)
To avoid corrupted files on crash, write to temporary file first:
ruby
require 'tempfile'
Tempfile.create('safe_write') do |temp_file|
temp_file.puts "Important data"
temp_file.puts "More important data"
temp_file.flush
# Now atomically replace the target file
File.rename(temp_file.path, "important.txt")
endWorking with Paths
用途 File.expand_path, File.join、 そして Pathname for robust path handling:
ruby
require 'pathname'
path = Pathname.new("/tmp") / "myapp" / "log.txt"
File.write(path, "Log entry")
# Or using File.join
full_path = File.join(Dir.home, "Documents", "notes.txt")Error Handling
Always handle potential errors:
ruby
begin
content = File.read("nonexistent.txt")
rescue Errno::ENOENT
puts "File not found!"
rescue Errno::EACCES
puts "Permission denied!"
rescue => e
puts "Error: #{e.message}"
endOr more idiomatically:
ruby
if File.exist?("config.txt")
config = File.read("config.txt")
else
puts "Config file missing, using defaults"
endBest Practices to Read and Write Files in Ruby
- Always use block form when possible – ensures file closure.
- 用途
File.read/File.writefor simple whole-file operations. - 用途
foreachfor large files to avoid loading everything into memory. - Specify encoding when working with non-ASCII text.
- Check file existence before reading if needed.
- Use appropriate modes (especially binary mode on Windows).
- Handle exceptions gracefully in production code.
結論
で レールカーマをリードしている。 Ruby on Rails開発会社, our expert developers leverage Ruby’s elegant file I/O capabilities to deliver robust and maintainable applications. Ruby’s clean syntax, block-based resource management, and powerful methods like File.read そして File.write make file handling in Ruby safe, efficient, and scalable.
Whether it’s processing configuration files, managing logs, generating reports, or building complex data pipelines, our Rails開発サービス ensure minimal boilerplate, maximum expressiveness, and high performance. By choosing to hire Ruby developers from RailsCarma, you gain access to skilled engineers who build reliable, high-quality Rails applications tailored to your business needs.