Common scenario: You are writing a basic Ruby script that needs to read or write in some text files.

So you search “ruby write file” and “ruby read file” on Google. You end up on the usual tutorials and Stack Overflow answers that tell you to open files with r or w mode, “1970 C style”. It works, but you may think: “I just want to read/write in a file, spare me the details!”.

I got you covered. Have a look at the code below. In all of these examples, Ruby automatically opens and closes the file. No need to think about it.

Read a whole file

content = File.read('input.txt')

Done.

Write to a file

File.write('output.txt', 'Hello world')

That’s it!

What if I want to …?

The above code covers most needs, but slightly here are some other less common scenarios.

Read a file line by line (useful if you don’t want to load a big file entirely in memory):

File.open('input.txt', 'r').each_line { |line| puts line }

Another way to do it is File.foreach('input.txt') { |line| puts line }, though I personally don’t find the word “foreach” very Ruby idiomatic.

Put the lines of a file in an array of lines:

lines = File.readlines('input.txt')

Append some text at the end of a file:

File.open('file.txt', 'a') { |file| file.write('some text') }

You can also do file << 'some text'. Or file.puts('some text') if you want to insert the text with a \n in the end.