Ruby on Rails - File I/O in Ruby
Introduction
File input/output (I/O) operations are essential for many applications, enabling them to read from and write to files. Ruby provides a rich set of methods for handling file I/O. This guide will cover the basics of working with file I/O in Ruby.
Key Points:
- File I/O operations are essential for many applications.
- Ruby provides a rich set of methods for handling file I/O.
- This guide covers the basics of working with file I/O in Ruby.
Reading from Files
Ruby provides several ways to read from files. Here are some examples:
# Read the entire file into a string
content = File.read('example.txt')
puts content
# Read the file line by line
File.open('example.txt', 'r') do |file|
file.each_line do |line|
puts line
end
end
# Read the file into an array of lines
lines = File.readlines('example.txt')
lines.each { |line| puts line }
In these examples, the entire file is read into a string, read line by line within a block, and read into an array of lines.
Writing to Files
Ruby also provides several ways to write to files. Here are some examples:
# Write to a file (overwrite existing content)
File.open('example.txt', 'w') do |file|
file.puts 'Hello, world!'
end
# Append to a file
File.open('example.txt', 'a') do |file|
file.puts 'Appended line.'
end
# Use File.write to write content
File.write('example.txt', 'Overwritten content.')
In these examples, the file is overwritten, appended to, and written to with new content.
File Modes
When opening a file, you can specify different modes to control how the file is accessed. Here are some common file modes:
'r'
: Read-only mode (default).'w'
: Write-only mode (overwrites existing content).'a'
: Append mode (adds to existing content).'r+'
: Read-write mode (does not truncate file).'w+'
: Read-write mode (truncates file).'a+'
: Read-append mode (adds to existing content).
# Open a file in read-write mode
File.open('example.txt', 'r+') do |file|
file.puts 'This is a read-write mode example.'
end
File Paths
Ruby provides methods for handling file paths. Here are some examples:
# Get the absolute path of a file
absolute_path = File.expand_path('example.txt')
puts absolute_path
# Join directory and file names into a single path
full_path = File.join('dir', 'subdir', 'example.txt')
puts full_path
# Check if a file exists
if File.exist?('example.txt')
puts 'File exists.'
else
puts 'File does not exist.'
end
In these examples, the absolute path of a file is obtained, directory and file names are joined into a single path, and the existence of a file is checked.
File Information
Ruby provides methods to retrieve information about files. Here are some examples:
# Get the size of a file in bytes
file_size = File.size('example.txt')
puts "File size: #{file_size} bytes"
# Get the last modified time of a file
last_modified = File.mtime('example.txt')
puts "Last modified: #{last_modified}"
In these examples, the size and last modified time of a file are retrieved.
Deleting and Renaming Files
Ruby allows you to delete and rename files. Here are some examples:
# Delete a file
File.delete('example.txt')
# Rename a file
File.rename('old_name.txt', 'new_name.txt')
In these examples, a file is deleted and another file is renamed.
Working with Directories
Ruby also provides methods for working with directories. Here are some examples:
# Create a directory
Dir.mkdir('new_directory')
# List files in a directory
files = Dir.entries('.')
puts files
# Change the current working directory
Dir.chdir('new_directory') do
puts "Current directory: #{Dir.pwd}"
end
In these examples, a new directory is created, files in the current directory are listed, and the current working directory is changed temporarily.
Handling File Errors
When working with files, it is important to handle potential errors. Here is an example:
# Handle file errors
begin
File.open('non_existent_file.txt', 'r')
rescue Errno::ENOENT => e
puts "File not found: #{e.message}"
end
In this example, an attempt to open a non-existent file is made, and the error is caught and handled gracefully.
Conclusion
Working with file I/O in Ruby is essential for many applications. This guide covered the basics of reading from and writing to files, using different file modes, handling file paths, retrieving file information, deleting and renaming files, working with directories, and handling file errors. With these techniques, you can effectively manage file I/O operations in your Ruby applications.