Ruby File Handling

Reading, writing, and managing files in Ruby

📁 What is File Handling?

File handling in Ruby allows you to create, read, write, and manipulate files on your system. Ruby provides simple and powerful methods for all file operations.


# Simple file write example
File.open("hello.txt", "w") do |file|
  file.write("Hello, Ruby!")
end

puts "File created successfully!"
                                    

Output:

File created successfully!

Key File Operations

📖

Reading Files

Read content from files

content = File.read("file.txt")
puts content
✍️

Writing Files

Write data to files

File.write("file.txt", "Hello")

Appending

Add content to existing files

File.open("file.txt", "a") do |f|
  f.puts "New line"
end
🔍

File Info

Check file properties

File.exist?("file.txt")
File.size("file.txt")

🔹 Reading Files

Ruby provides multiple ways to read files. You can read the entire file at once, read it line by line, or use a block to automatically close the file after reading.

# Method 1: Read entire file
content = File.read("example.txt")
puts content

# Method 2: Read with block (auto-closes file)
File.open("example.txt", "r") do |file|
  content = file.read
  puts content
end

# Method 3: Read line by line
File.foreach("example.txt") do |line|
  puts line
end

# Method 4: Read all lines into array
lines = File.readlines("example.txt")
puts "Total lines: #{lines.length}"

Output:

This is line 1
This is line 2
This is line 3
Total lines: 3

🔹 Writing to Files

You can write to files using different modes: 'w' for write (overwrites existing content), 'a' for append (adds to existing content), and 'w+' for read and write. Always use blocks to ensure files are properly closed.

# Method 1: Simple write (overwrites file)
File.write("output.txt", "Hello, World!")

# Method 2: Write with block
File.open("output.txt", "w") do |file|
  file.puts "Line 1"
  file.puts "Line 2"
  file.write("Line 3\n")
end

# Method 3: Append to file
File.open("output.txt", "a") do |file|
  file.puts "Line 4 - appended"
end

# Read back to verify
puts File.read("output.txt")

Output:

Line 1
Line 2
Line 3
Line 4 - appended

🔹 File Modes

Different file modes control how files are opened and what operations are allowed. Understanding these modes is crucial for proper file handling and preventing data loss or corruption.

# "r" - Read only (file must exist)
File.open("data.txt", "r") { |f| puts f.read }

# "w" - Write only (creates new or truncates existing)
File.open("data.txt", "w") { |f| f.write("New content") }

# "a" - Append (creates new or adds to existing)
File.open("data.txt", "a") { |f| f.puts("Added line") }

# "r+" - Read and write (file must exist)
File.open("data.txt", "r+") do |f|
  content = f.read
  f.rewind
  f.write("Updated: #{content}")
end

# "w+" - Read and write (creates new or truncates)
File.open("data.txt", "w+") do |f|
  f.write("Fresh start")
  f.rewind
  puts f.read
end

Common File Modes:

r  - Read only
w  - Write (overwrites)
a  - Append
r+ - Read and write
w+ - Read and write (overwrites)
a+ - Read and append

🔹 File Information

Ruby provides many methods to check file properties and status. These methods help you verify file existence, check permissions, get file size, and retrieve modification times before performing operations.

filename = "example.txt"

# Check if file exists
if File.exist?(filename)
  puts "File exists!"
  
  # Get file size
  puts "Size: #{File.size(filename)} bytes"
  
  # Check if it's a file (not directory)
  puts "Is file: #{File.file?(filename)}"
  
  # Check if readable/writable
  puts "Readable: #{File.readable?(filename)}"
  puts "Writable: #{File.writable?(filename)}"
  
  # Get file timestamps
  puts "Created: #{File.ctime(filename)}"
  puts "Modified: #{File.mtime(filename)}"
  
  # Get absolute path
  puts "Path: #{File.absolute_path(filename)}"
else
  puts "File does not exist"
end

Output:

File exists!
Size: 1024 bytes
Is file: true
Readable: true
Writable: true
Created: 2025-01-15 10:30:00
Modified: 2025-01-15 14:20:00
Path: /home/user/example.txt

🔹 File Operations

Beyond reading and writing, Ruby provides methods for copying, moving, renaming, and deleting files. These operations are essential for file management tasks in your applications.

require 'fileutils'

# Create a file
File.write("original.txt", "Original content")

# Copy file
FileUtils.cp("original.txt", "copy.txt")
puts "File copied"

# Rename/Move file
File.rename("copy.txt", "renamed.txt")
puts "File renamed"

# Delete file
File.delete("renamed.txt") if File.exist?("renamed.txt")
puts "File deleted"

# Check file existence
if File.exist?("original.txt")
  puts "Original file still exists"
end

# Get file extension and basename
path = "documents/report.pdf"
puts "Extension: #{File.extname(path)}"
puts "Basename: #{File.basename(path)}"
puts "Directory: #{File.dirname(path)}"

Output:

File copied
File renamed
File deleted
Original file still exists
Extension: .pdf
Basename: report.pdf
Directory: documents

🧠 Test Your Knowledge

Which file mode appends content without overwriting?