Ruby - Create New File and Write Content

1. Introduction

File I/O (Input/Output) is a fundamental concept in programming. In Ruby, working with files is straightforward thanks to its high-level I/O classes. In this post, we'll look at how to create a new file and write content to it using Ruby.

Definition

File I/O refers to the processes of reading data from and writing data to files. Ruby provides the File class, which offers a suite of methods for file operations. For this tutorial, we'll focus on creating a new file and writing data to it.

2. Program Steps

1. Use the File class to open or create a new file.

2. Write content to the file.

3. Close the file to ensure all data is saved and resources are released.

3. Code Program

# Open a new file or create one if it doesn't exist, then write content to it
File.open('sample.txt', 'w') do |file|
  # Write multiple lines to the file
  file.puts("Hello, World!")
  file.puts("This is a sample text.")
end
# Print a message after writing to the file
puts "Content has been written to sample.txt."

Output:

Content has been written to sample.txt.

Explanation:

1. The File.open method is used to open a file. The first argument is the file name (sample.txt in this case), and the second argument 'w' specifies the mode in which the file is opened. Here, 'w' stands for "write mode," which allows data to be written to the file. If the file already exists, this mode will overwrite it. If it doesn't exist, a new file will be created.

2. The do |file| ... end block ensures that the file is automatically closed once operations within the block are completed. This pattern is considered best practice in Ruby because it ensures proper file closure and resource management.

3. The file.puts method is used to write lines of text to the file. Each call to puts writes a new line.

4. Once the block completes, the file is closed, and a confirmation message is printed to the console.

Using Ruby's built-in File class, it becomes incredibly simple to perform file operations, ensuring that data is stored persistently and can be accessed later.


Comments