Tsallaka zuwa abun ciki
Justice Tech School

Ruby File I/O

File.open with a block closes the file automatically. Methods: read, write, readlines, each_line, exist?, delete and Dir for folders.

Example
require "tmpdir"
path = File.join(Dir.tmpdir, "ruby_files_demo.txt")
File.write(path, "a\nb\n")
File.open(path, "a") { |f| f.puts "c" }
puts File.readlines(path, chomp: true).inspect
File.foreach(path) { |l| print l.upcase }
puts File.exist?(path), File.size(path)
File.delete(path)

Result

["a", "b", "c"]
A
B
C
true
6

Exercise

Append mode.

File.open(path, "")

Quiz Test

Why pass a block to File.open?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.