Reading and writing files
Read project files with File.read and CSV, write JSON, and keep temporary files under /tmp.
Runs in Zerethon IDE · Ruby 4.0
Official Ruby documentation ↗
A run sees the project's files in its working folder, read-only. A program may write files under /tmp; they are deleted when the run ends.
main.rb
require "csv"
require "json"
rows = CSV.read("data.csv", headers: true)
puts rows.map { |row| row["name"] }.inspect
File.write("/tmp/report.json", JSON.generate({ count: rows.size }))
puts JSON.parse(File.read("/tmp/report.json"))["count"]
File.foreach("data.csv").with_index do |line, i|
puts "#{i}: #{line.chomp}"
end
data.csv
name,score
ada,90
alan,85
Output
["ada", "alan"] 2 0: name,score 1: ada,90 2: alan,85
File.readandFile.writeopen and close the file for you;File.open(path) { |f| ... }closes it when the block ends.- Paths are relative to the project root:
File.read("data/input.txt")reads the file shown in the explorer asdata/input.txt. - Writing next to your code (
File.write("out.txt", ...)) fails withRead-only file system— use/tmp/out.txt. jsonandcsvcome with Ruby;JSON.parsegives string keys unless you passsymbolize_names: true.