In this section, we will explore how to handle file input and output (I/O) in Ruby. File I/O is a crucial part of many applications, allowing you to read from and write to files, which is essential for data persistence.

Key Concepts

  1. Opening Files: How to open files for reading, writing, or both.
  2. Reading Files: Different methods to read data from files.
  3. Writing Files: How to write data to files.
  4. Closing Files: Ensuring files are properly closed after operations.
  5. File Modes: Understanding different file modes (read, write, append, etc.).
  6. File Operations: Additional operations like renaming, deleting, and checking file existence.

Opening Files

To open a file in Ruby, you use the File.open method. This method can take a file path and a mode as arguments.

file = File.open("example.txt", "r") # Opens the file in read mode

File Modes

Mode Description
"r" Read-only mode
"w" Write-only mode (truncates existing file)
"a" Append mode
"r+" Read and write mode
"w+" Read and write mode (truncates existing file)
"a+" Read and append mode

Reading Files

Ruby provides several methods to read data from a file:

Reading the Entire File

content = File.read("example.txt")
puts content

Reading Line by Line

File.open("example.txt", "r") do |file|
  file.each_line do |line|
    puts line
  end
end

Reading with IO.readlines

lines = IO.readlines("example.txt")
lines.each { |line| puts line }

Writing Files

To write data to a file, you can use the File.write method or open the file in write mode and use puts or write.

Using File.write

File.write("example.txt", "Hello, World!")

Using File.open with Write Mode

File.open("example.txt", "w") do |file|
  file.puts "Hello, World!"
end

Closing Files

When you open a file, it's important to close it to free up system resources. Using a block with File.open ensures the file is closed automatically.

file = File.open("example.txt", "r")
# Perform file operations
file.close

Using a block:

File.open("example.txt", "r") do |file|
  # Perform file operations
end # File is automatically closed here

Additional File Operations

Checking File Existence

if File.exist?("example.txt")
  puts "File exists."
else
  puts "File does not exist."
end

Renaming a File

File.rename("example.txt", "new_example.txt")

Deleting a File

File.delete("example.txt")

Practical Exercise

Exercise: File I/O Operations

  1. Create a new file named test.txt and write the following content to it:

    Line 1
    Line 2
    Line 3
    
  2. Read the content of test.txt and print each line to the console.

  3. Append the following line to test.txt:

    Line 4
    
  4. Rename test.txt to final_test.txt.

  5. Check if final_test.txt exists and print a confirmation message.

Solution

# Step 1: Create and write to the file
File.open("test.txt", "w") do |file|
  file.puts "Line 1"
  file.puts "Line 2"
  file.puts "Line 3"
end

# Step 2: Read and print the file content
File.open("test.txt", "r") do |file|
  file.each_line do |line|
    puts line
  end
end

# Step 3: Append a new line to the file
File.open("test.txt", "a") do |file|
  file.puts "Line 4"
end

# Step 4: Rename the file
File.rename("test.txt", "final_test.txt")

# Step 5: Check if the file exists
if File.exist?("final_test.txt")
  puts "final_test.txt exists."
else
  puts "final_test.txt does not exist."
end

Conclusion

In this section, we covered the basics of file I/O in Ruby, including how to open, read, write, and close files. We also explored additional file operations like renaming and deleting files. Understanding these concepts is essential for handling data persistence in your Ruby applications. In the next section, we will delve into regular expressions, a powerful tool for pattern matching and text manipulation.

© Copyright 2024. All rights reserved