Tsallaka zuwa abun ciki
Justice Tech School

Reading and Writing Files

File.write, File.read and File.foreach handle files. Use blocks so files close.

Example
path = "/tmp/demo_rb.txt"
File.write(path, "one\ntwo\n")
puts File.read(path).lines.map(&:chomp).inspect
File.foreach(path) { |l| puts "> #{l}" }
File.delete(path)

Result

["one", "two"]
> one
> two

Exercise

Write a file.

File.(path, "x")

Quiz Test

Why use blocks with File.open?

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