Ruby - Writing to Files

Introduction

You can use the following techniques to write to files.

Demo

File.open("test.txt", "w") do |f| 
  f.puts "This is a test" 
end

This code creates a new file or overwrites an existing file called text.txt and puts a single line of text within it.

File.puts writes the data to the file instead.

The "w" tells Ruby to open the file for writing only, and to create a new file or overwrite what is already in the file.

We used "r" mode to open a file for reading only.

Related Topic