Ruby - Different File Modes

1. Introduction

In Ruby, when working with files, you often need to specify the mode in which you want to open a file, whether it's for reading, writing, appending, or a combination of these operations. This post will guide you through different file modes and demonstrate how to use them.

File modes determine how the file is to be opened. Different modes allow for reading, writing, or both. They also determine the behavior of the file, for example, whether data written to the file replaces its existing content or is added to it.

2. Program Steps

1. Open a file in different modes.

2. Perform operations as per the mode.

3. Close the file after operations are completed.

3. Code Program

# Opening a file in read mode
file = File.open('sample.txt', 'r')
content = file.read
puts "Reading file in read mode: \n#{content}"
file.close

# Opening a file in write mode
file = File.open('sample.txt', 'w')
file.puts("This is a new line.")
file.close

# Opening a file in append mode
file = File.open('sample.txt', 'a')
file.puts("Appending this line.")
file.close

# Reading the file after all operations
file = File.open('sample.txt', 'r')
content = file.read
puts "\nContent after all operations: \n#{content}"
file.close

Output:

Reading file in read mode:
Original content of the file.
Content after all operations:
This is a new line.
Appending this line.

Explanation:

1. The File.open method is used to open a file with a specified mode. The first parameter is the filename and the second is the mode.

2. 'r' mode: Opens the file in read-only mode. Attempting to write to the file in this mode will result in an error.

3. 'w' mode: Opens the file for writing only. It truncates the file to zero length or creates a new file if it doesn't exist.

4. 'a' mode: Opens the file for writing only. It creates the file if it doesn't exist. Data is appended to the file if it exists.

5. The file.read method reads the entire content of the file.

6. The file.puts method writes a string to the file followed by a newline.

7. Always remember to close the file using the file.close method once operations are done.

By understanding and using different file modes, you can effectively manage file operations in Ruby.


Comments