Ruby - Using file mode

Introduction

The following code creates a program that appends a line of text to a file:

Demo

f = File.new("logfile.txt", "a") 
f.puts Time.now 
f.close

If you run this code multiple times, logfile.txt will contain several dates and times.

Append mode is ideal for log file situations where new information has to be added at different times.

To open a file in a mode where it can be read from and written to at the same time, you can do just that:

Demo

f = File.open("main.rb", "r+") 
puts f.gets #   ww w .j av  a  2  s . co m
f.puts "This is a test" 
puts f.gets 
f.close

Result

The second line of this code reads the first line of text from the file.

The file pointer is waiting at the start of the second line of data.

However, the following f.puts statement then puts a new line of text into the file at that position.

You can read character via getc and write via putc:

putc and write overwrite existing content in the file rather than inserting it.

The code above opens text.txt for reading and writing, and changes the first character of the first line to X.

Demo

f = File.open("main.rb", "r+") 
f.putc "X" 
f.close

This following example overwrites the first six characters of the first line with 123456.

Demo

f = File.open("main.rb", "r+") 
f.write "123456" 
f.close

Related Topic