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
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.