Read and Write Files in Ruby

How To Read and Write Files in Ruby (With Examples)

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 here

Without a block, you must manually close the file:

ruby
file = File.open("filename.txt", "r")
# ... operations ...
file.close

File Modes

The second argument to File.open is the mode string:

ModeMeaning
“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 content

Or 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}"
end

3. 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
end

Or using the shorter foreach:

ruby
File.foreach("large_file.txt") do |line|
  process(line.chomp)
end

4. 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 }
end

Writing 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"
end

Methods available inside the block:

  • puts – adds newline
  • print – no newline
  • write – 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
end
Example 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}"
end
Example 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").size
Example 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")
end

Working 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}"
end

Or more idiomatically:

ruby
if File.exist?("config.txt")
  config = File.read("config.txt")
else
  puts "Config file missing, using defaults"
end

Best Practices to Read and Write Files in Ruby

  1. Always use block form when possible – ensures file closure.
  2. 用途 File.read/File.write for simple whole-file operations.
  3. 用途 foreach for large files to avoid loading everything into memory.
  4. Specify encoding when working with non-ASCII text.
  5. Check file existence before reading if needed.
  6. Use appropriate modes (especially binary mode on Windows).
  7. 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.

関連記事

投稿者について

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です


jaJapanese