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.read and File.write open 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 as data/input.txt.
  • Writing next to your code (File.write("out.txt", ...)) fails with Read-only file system — use /tmp/out.txt.
  • json and csv come with Ruby; JSON.parse gives string keys unless you pass symbolize_names: true.