File handling is a crucial aspect of many Ruby programs. Understanding how to open and close files properly is essential for efficient and safe file operations.
Ruby provides several ways to open files. The most common method is using the File.open
method.
file = File.open("example.txt", "r")
# Perform operations on the file
file.close
In this example, "r" specifies read mode. Other common modes include "w" for write and "a" for append.
A more idiomatic Ruby approach is to use a block, which automatically closes the file when the block ends:
File.open("example.txt", "r") do |file|
# Perform operations on the file
end
# File is automatically closed here
This method is preferred as it ensures the file is closed even if an exception occurs.
Once a file is open, you can read its contents using various methods:
File.open("example.txt", "r") do |file|
contents = file.read
puts contents
end
For line-by-line reading, you can use the each_line
method:
File.open("example.txt", "r") do |file|
file.each_line do |line|
puts line
end
end
To write to a file, open it in write mode:
File.open("output.txt", "w") do |file|
file.write("Hello, Ruby!")
end
File.exist?
to check if a file exists before opening it.To further enhance your understanding of file operations in Ruby, explore these related topics:
By mastering file open and close operations, you'll be well-equipped to handle various file-related tasks in your Ruby programs efficiently and safely.