Ruby - Append Data to an Existing File

1. Introduction

Appending data to an existing file is a common operation in programming. Instead of overwriting the current content, you may want to add new data at the end of the file. In Ruby, appending data to a file is straightforward and efficient using the built-in File class.

Appending data to a file means adding new content to the end of the existing file content without altering the original data. This operation ensures data integrity by preserving the previous data while also allowing the inclusion of new information.

2. Program Steps

1. Use the File class to open an existing file in append mode.

2. Write new content to the file.

3. Close the file to ensure data integrity and resource management.

3. Code Program

# Open an existing file in append mode and add new content
File.open('sample.txt', 'a') do |file|
  # Append new data to the file
  file.puts "\nAppended data: Ruby is wonderful!"
end
# Print a confirmation message after appending to the file
puts "Data has been appended to sample.txt."

Output:

Data has been appended to sample.txt.

Explanation:

1. The File.open method is utilized to open the existing file. The first argument, sample.txt, specifies the filename, while the second argument, 'a', indicates the mode in which the file should be opened. Here, 'a' represents the "append mode," which allows data to be added to the end of the file without overwriting the existing content.

2. Using the do |file| ... end block pattern ensures the file is automatically closed after operations inside the block are executed. This is the best practice in Ruby to manage file resources efficiently.

3. Within the block, the file.puts method is employed to append a new line of data to the file.

4. After the block completes, the file is closed, and a confirmation message is shown in the console.

Ruby's File class makes the process of appending data to files effortless and intuitive, ensuring that previous data remains untouched while new information can be efficiently added.


Comments