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.
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
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
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
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
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
To create a new directory, you can use the Dir.mkdir
method:
Dir.mkdir('new_directory')
To list all files in a directory, you can use the Dir.entries
method:
files = Dir.entries('.')
puts files
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.
© 2024 RailsInsights. All rights reserved.