We use IO modes to tell the computer how we want to open a file: to read, write, or add more content.
0
0
IO modes (r, w, a) in Ruby
Introduction
When you want to read information from a file, like reading a list of names.
When you want to create a new file or replace everything in an existing file with new content.
When you want to add new information to the end of an existing file without deleting what is already there.
Syntax
Ruby
File.open('filename', 'mode') do |file| # work with file here end
'r' means open the file for reading only.
'w' means open the file for writing, and it will erase the file if it exists or create a new one.
'a' means open the file for appending, so new content is added at the end.
Examples
This reads and prints the whole content of 'example.txt'.
Ruby
File.open('example.txt', 'r') do |file| content = file.read puts content end
This writes 'Hello, world!' to 'example.txt', erasing old content.
Ruby
File.open('example.txt', 'w') do |file| file.puts 'Hello, world!' end
This adds a new line at the end of 'example.txt' without removing old content.
Ruby
File.open('example.txt', 'a') do |file| file.puts 'Adding a new line.' end
Sample Program
This program first writes two lines to a file, then adds a third line, and finally reads and prints all lines.
Ruby
filename = 'testfile.txt' # Write mode: create or overwrite file File.open(filename, 'w') do |file| file.puts 'Line 1' file.puts 'Line 2' end # Append mode: add more lines File.open(filename, 'a') do |file| file.puts 'Line 3' end # Read mode: read and print all lines File.open(filename, 'r') do |file| file.each_line do |line| puts line.chomp end end
OutputSuccess
Important Notes
Using 'w' mode deletes old file content, so be careful if you want to keep it.
Using 'a' mode keeps old content and adds new content at the end.
Always close files or use blocks (do...end) to close automatically.
Summary
'r' mode is for reading files without changing them.
'w' mode is for writing files and erases old content.
'a' mode is for adding new content to the end of files.