Rails Insights

How To Work with Files In Ruby

Introduction

Working with files is a common task in programming, and Ruby provides a variety of tools and methods to make it easy to read, write, and manipulate files. In this article, we will explore how to work with files in Ruby, including reading and writing files, handling exceptions, and more.

Reading Files

Reading a File Line by Line

One common task when working with files is reading the contents line by line. This can be done using the File.foreach method:

File.foreach('example.txt') do |line|
  puts line
end

Reading the Entire File

If you want to read the entire contents of a file into a single string, you can use the File.read method:


contents = File.read('example.txt')
puts contents

Writing Files

Writing to a File

To write to a file, you can use the File.open method with the 'w' mode:

File.open('output.txt', 'w') do |file|
  file.puts "Hello, world!"
end

Appending to a File

If you want to append to an existing file, you can use the 'a' mode:

File.open('output.txt', 'a') do |file|
  file.puts "This is a new line."
end

Handling Exceptions

Rescuing Exceptions

When working with files, it's important to handle exceptions that may occur, such as file not found or permission denied. You can use the rescue keyword to catch and handle exceptions:

begin
  File.open('nonexistent.txt', 'r') do |file|
    puts file.read
  end
rescue Errno::ENOENT
  puts "File not found."
end

Working with Directories

Creating a Directory

To create a new directory, you can use the Dir.mkdir method:

Dir.mkdir('new_directory')

Listing Files in a Directory

To list all files in a directory, you can use the Dir.entries method:

files = Dir.entries('.')
puts files

Conclusion

Working with files in Ruby is a fundamental skill for any Ruby programmer. By using the methods and techniques outlined in this article, you can easily read, write, and manipulate files in your Ruby programs. Remember to handle exceptions and errors gracefully to ensure your programs are robust and reliable.

Published: April 27, 2024

© 2024 RailsInsights. All rights reserved.