Files and IO

Read a whole file

The method File.read loads a whole file into one string, which suits small configs and study scripts. Reading huge logs this way can exhaust memory, so treat it as the small file tool. The script below reads its own source file, so it runs in any folder.

text = File.read(__FILE__) puts text.empty?

false

Iterate lines

The iterator File.foreach yields each line in turn while keeping memory flat. Every line keeps its trailing newline, and chomp trims it away. Prefer this form for logs and dumps of unknown size.

File.write("demo.txt", "a\nb\n") File.foreach("demo.txt") do |line| puts line.chomp end

a
b

Write files

The method File.write replaces the whole file content with the given string. Opening with mode w in a block serves several writes in one session. Newlines never appear on their own: every line break comes from the strings you pass.

File.write("demo.txt", "hello") puts File.read("demo.txt")

hello

List a directory

The method Dir.children lists the names inside a folder. The predicate Dir.exist? checks that a folder is present before touching it. The method File.join assembles folder and file names into a correct path on any system.

names = Dir.children(".") puts names.is_a?(Array) puts Dir.exist?(".")

true
true

Next: Reading and writing files

Article author: Arthur Isaev

Banner image