File Handling in Ruby: Reading and Writing Files
Introduction to File Handling
File handling is a common task in programming. In Ruby, you can easily work with files to read data from them or write data to them. This is essential for tasks like data input/output, configuration files, and log files. In this guide, we'll explore how to perform file handling in Ruby with examples.
Reading Files
You can read the contents of a file in Ruby using the File.open
method. Here's an example:
# Open the file in read mode
File.open("sample.txt", "r") do |file|
contents = file.read
puts contents
end
In this example, we open the file "sample.txt" in read mode, read its contents, and print them to the console.
Writing Files
You can write data to a file in Ruby using the File.open
method with the write mode. Here's an example:
# Open the file in write mode (creates a new file if it doesn't exist)
File.open("output.txt", "w") do |file|
file.write("Hello, world!")
end
In this example, we open or create a file "output.txt" in write mode and write the text "Hello, world!" to the file. Be careful with write mode, as it overwrites the file's contents if it already exists.
Appending to Files
If you want to add data to an existing file without overwriting it, you can use append mode. Here's an example:
# Open the file in append mode (creates a new file if it doesn't exist)
File.open("log.txt", "a") do |file|
file.puts("New log entry")
end
In this example, we open or create a file "log.txt" in append mode and add a new log entry to the end of the file.
Conclusion
File handling is a fundamental part of many Ruby applications. Whether you need to read data from files, write data to files, or append data to existing files, Ruby provides convenient methods for these tasks. Understanding file handling is essential for building data-driven and file-based applications.
Practice file handling in your Ruby programs to become a proficient Ruby developer. For more information, refer to the official Ruby documentation.
Happy coding!