Ruby
File I/O
Read, write, append, traverse directories, and process CSV files.
By EZ4Code Team
fileiocsv
Code
# Write text
File.write("data.txt", "line 1\nline 2\n")
# Read entire file
puts File.read("data.txt")
# Read line by line (auto-closes)
File.foreach("data.txt") { |line| puts "[#{line.chomp}]" }
# Append
File.open("data.txt", "a") { |f| f.puts "line 3" }
# File info
puts File.exist?("data.txt")
puts File.size("data.txt")
# Path operations
puts File.basename("/a/b/c.txt") # c.txt
puts File.dirname("/a/b/c.txt") # /a/b
puts File.extname("c.txt") # .txt
puts File.join("a", "b", "c.txt")
# Directory traversal
Dir.mkdir("samples") unless Dir.exist?("samples")
Dir.glob("*.txt").each { |f| puts f }
# CSV with stdlib
require "csv"
CSV.open("people.csv", "w") do |csv|
csv << %w[name age]
csv << ["Alice", 30]
end
CSV.foreach("people.csv", headers: true) do |row|
puts "#{row['name']} is #{row['age']}"
endExplanation
File.write and File.read cover one-shot text I/O, while File.foreach streams large files line by line without loading them into memory. The block form of File.open closes the handle automatically even on errors. The csv stdlib handles both writing rows and reading with headers out of the box.
More Ruby Snippets
Blocks, Procs, Lambdas
Use blocks with yield, Procs, lambdas, and the & operator.
Classes and Modules
Define classes with inheritance, mix in modules, and add class methods.
Iterators
Use each, map, select, reduce, group_by, and lazy enumerators.
Strings
Interpolate, trim, split, replace, and pattern-match strings.
Hashes
Build, default, transform, merge, and group with Hash.
Metaprogramming
Define methods dynamically, intercept with method_missing, and build DSLs.