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 ='sample.txt', 'r')
content =
puts "Reading file in read mode: \n#{content}"

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

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

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


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


1. The 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 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.