Ruby File Handling

This chapter explores Ruby file handling, which allows reading from and writing to files. File handling is essential for tasks that involve data storage, retrieval, and manipulation in applications.

Chapter Goals

  • Understand the purpose and methods for file handling in Ruby.
  • Learn how to open, read, write, and close files.
  • Explore advanced file operations like appending and file existence checks.
  • Implement best practices for safe and efficient file handling.

Key Characteristics of Ruby File Handling

  • Flexibility: Provides multiple modes for reading, writing, and appending to files.
  • Built-in Methods: Offers a variety of methods for file operations.
  • Safety: Encourages using blocks to ensure files are properly closed.
  • Platform Independence: Abstracts file operations for cross-platform compatibility.

Basic Rules for File Handling

  • Always close files after operations to release system resources.
  • Use blocks for file operations to ensure automatic file closure.
  • Check file existence before attempting to read or write.
  • Handle exceptions to prevent crashes during file operations.

Best Practices

  • Use descriptive filenames and paths for better organization.
  • Prefer block-based file handling for safety and simplicity.
  • Validate input and output paths to avoid unintended overwrites.
  • Handle errors gracefully with exception handling.
  • Test file operations with various edge cases (e.g., empty files, non-existent files).

Syntax Table

Serial No Operation Syntax/Example Description
1 Open File for Reading File.open(‘filename’, ‘r’) Opens a file in read mode.
2 Open File for Writing File.open(‘filename’, ‘w’) Opens a file in write mode.
3 Open File for Appending File.open(‘filename’, ‘a’) Opens a file in append mode.
4 Read File Content File.read(‘filename’) Reads the entire file content.
5 Write to File file.write(‘text’) Writes text to a file.
6 File Existence Check File.exist?(‘filename’) Checks if a file exists.

Syntax Explanation

Opening and Closing Files

What is File Opening?

Opening a file establishes a connection between the program and the file for reading or writing.

Syntax

file = File.open(‘filename’, ‘mode’)

file.close

Detailed Explanation

  • Modes include:
    • ‘r’: Read-only.
    • ‘w’: Write-only (overwrites existing content).
    • ‘a’: Append-only.
  • The close method releases the file resource after operations.
  • Using File.open with a block ensures the file is automatically closed after the block executes.

Example

file = File.open(‘example.txt’, ‘w’)

file.write(‘Hello, World!’)

file.close

Example Explanation

  • Opens example.txt in write mode, writes text to it, and then closes the file.

Block-Based Example

File.open(‘example.txt’, ‘w’) do |file|

  file.write(‘Hello, Block-Based File Handling!’)

end

Explanation of Block-Based Example

  • Automatically closes the file after the block executes, reducing the risk of resource leaks.

Reading from Files

What is File Reading?

Reading a file retrieves its content for use in the program.

Syntax

content = File.read(‘filename’)

Detailed Explanation

  • Reads the entire file content into a string.
  • Suitable for small to medium-sized files.
  • For line-by-line processing, use File.foreach or File.readlines.

Example

content = File.read(‘example.txt’)

puts content

Example Explanation

  • Reads and outputs the content of example.txt.

Line-by-Line Example

File.foreach(‘example.txt’) do |line|

  puts line

end

Explanation of Line-by-Line Example

  • Processes the file line by line, which is memory-efficient for large files.

Writing to Files

What is File Writing?

Writing to a file stores data in the file.

Syntax

File.open(‘filename’, ‘w’) do |file|

  file.write(‘text’)

end

Detailed Explanation

  • Opens the file in write mode, writes the text, and automatically closes it.
  • Overwrites existing content in the file.
  • For appending without overwriting, use the ‘a’ mode.

Example

File.open(‘example.txt’, ‘w’) do |file|

  file.write(‘New Content’)

end

Example Explanation

  • Writes “New Content” to example.txt, overwriting any previous content.

Writing Multiple Lines Example

File.open(‘example.txt’, ‘w’) do |file|

  file.puts(‘Line 1’)

  file.puts(‘Line 2’)

end

Explanation of Multiple Lines Example

  • Writes each string on a new line using puts.

Appending to Files

What is File Appending?

Appending adds data to the end of a file without overwriting existing content.

Syntax

File.open(‘filename’, ‘a’) do |file|

  file.write(‘text’)

end

Detailed Explanation

  • Opens the file in append mode and writes text to the end of the file.
  • Does not overwrite existing content.

Example

File.open(‘example.txt’, ‘a’) do |file|

  file.write(‘Additional Content’)

end

Example Explanation

  • Appends “Additional Content” to example.txt.

Checking File Existence

What is File Existence Checking?

Checks if a file exists before performing operations on it.

Syntax

File.exist?(‘filename’)

Detailed Explanation

  • Returns true if the file exists, false otherwise.
  • Useful for avoiding errors when attempting to access non-existent files.

Example

if File.exist?(‘example.txt’)

  puts ‘File exists!’

else

  puts ‘File not found.’

end

Example Explanation

  • Outputs “File exists!” if example.txt is present, otherwise “File not found.”.

Combined Example with File Reading

if File.exist?(‘example.txt’)

  puts File.read(‘example.txt’)

else

  puts ‘File not found.’

end

Explanation of Combined Example

  • Reads and prints the file content only if the file exists.

Real-Life Project

Project Name: Simple Logger

Project Goal

Create a program to log messages to a file, including timestamps.

Code for This Project

def log_message(filename, message)

  File.open(filename, 'a') do |file|

    file.puts("[\#{Time.now}] \#{message}")

  end

end




log_message('log.txt', 'Application started.')

log_message('log.txt', 'User logged in.')

log_message('log.txt', 'Application terminated.')

Steps

  1. Define a method log_message that takes a filename and a message as input.
  2. Open the file in append mode.
  3. Write the message to the file, prefixed with a timestamp.
  4. Call the method with different messages to simulate logging.

Expected Output in log.txt

[2023-12-01 10:00:00] Application started.

[2023-12-01 10:05:00] User logged in.

[2023-12-01 10:10:00] Application terminated.

Project Explanation

  • Demonstrates appending data to a file with timestamps.
  • Highlights practical use cases for file handling in logging.

Insights

Ruby file handling provides powerful tools for managing data storage and retrieval. Understanding these tools ensures efficient and reliable file operations.

Key Takeaways

  • Use blocks for file operations to ensure automatic file closure.
  • Validate file existence to avoid runtime errors.
  • Choose appropriate file modes (r, w, a) based on the operation.
  • Combine file handling with methods and loops for practical applications.