File I/O in Ruby Language
File Input/Output (I/O) is a fundamental aspect of programming that allows you to work with files, whether it’s reading data from files, writing data to files, or manipulating f
iles in various ways. In the Ruby programming language, working with files is straightforward and offers a wide range of options for managing your data. In this post, we will explore the basics of File I/O in Ruby with examples.Reading from a File
To read data from a file in Ruby, you can use the File
class. Here’s an example of how to open a file and read its contents:
# Open a file for reading
file = File.open("example.txt", "r")
# Read the contents of the file
content = file.read
# Close the file
file.close
# Print the content
puts content
In this example, we first open the file “example.txt” in read mode ("r"
), read its content, and then close the file to free up system resources.
Writing to a File
To write data to a file, you can also use the File
class. Here’s an example:
# Open a file for writing (creates the file if it doesn't exist)
file = File.open("output.txt", "w")
# Write data to the file
file.puts("Hello, Ruby!")
file.puts("File I/O is fun!")
# Close the file
file.close
In this code, we open a file named “output.txt” in write mode ("w"
), write some lines to it using the puts
method, and then close the file to save the changes.
File Modes
Ruby offers various file modes for different operations:
"r"
: Read (default mode)."w"
: Write (creates a new file or truncates an existing file)."a"
: Append (writes to the end of an existing file or creates a new file)."r+"
: Read and Write."b"
: Binary mode (e.g.,"rb"
or"wb"
for reading and writing binary files).
Reading Line by Line
You can also read a file line by line, which is useful for large files to avoid loading the entire content into memory:
# Open a file for reading
file = File.open("example.txt", "r")
# Read and process each line
file.each_line do |line|
puts line
end
# Close the file
file.close
Handling Exceptions
When working with files, it’s essential to handle exceptions, such as when a file doesn’t exist or you don’t have permission to access it. Here’s how you can do it:
begin
file = File.open("nonexistent.txt", "r")
content = file.read
file.close
rescue Errno::ENOENT
puts "File not found."
rescue Errno::EACCES
puts "Permission denied."
end
In this example, we use the begin
and rescue
blocks to catch exceptions and handle them gracefully.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.