IO 与 Enumerable
File/Regex/Enumerable。
IO 与 Enumerable
这一课你将能做到
- 用 File 类读写文件、遍历目录,理解 File.open 的 block 自动关闭模式
- 用正则表达式匹配、提取、替换字符串,掌握 Ruby 特有的
=~和命名捕获 - 熟练使用 Enumerable 的 20+ 个核心方法做集合变换、过滤、分组、排序
为什么要学
IO 和集合操作是日常开发的「水电煤」。读日志、解析 CSV、处理 JSON、批量转换数据——Ruby 的 File API 和 Enumerable 模块就是为此而生。Enumerable 是 Ruby 最强大的模块,Array、Hash、Range 都 include 它,学会它等于学会了所有集合类的操作。
人话:File 是「读写外部世界」的接口,Enumerable 是「加工内部数据」的流水线。File.open 的 block 模式保证文件一定关闭,不会泄露句柄;Enumerable 的 map/select/reduce 让你用声明式风格处理数据,不用手写循环。
先建立图像
Enumerable 核心方法分类
┌─────────────┬─────────────────────────────────────┐
│ 变换 │ map, flat_map, compact, uniq, sort │
│ 过滤 │ select, reject, find, take_while │
│ 聚合 │ reduce/inject, sum, count, min/max │
│ 分组 │ group_by, partition, chunk_while │
│ 判断 │ all?, any?, none?, include? │
│ 遍历 │ each, each_with_index, each_slice │
└─────────────┴─────────────────────────────────────┘
File 打开模式
"r" 只读(默认) "w" 只写,清空原内容
"a" 追加 "r+" 读写,不清空
跟着做
步骤 1:File 读写——block 模式最安全
# 推荐:block 模式,自动关闭文件
File.open("test.txt", "w") do |f|
f.puts "第一行"
f.puts "第二行"
end
# 读取整个文件
content = File.read("test.txt")
puts content
# 逐行读取(大文件推荐,不一次性加载内存)
File.foreach("test.txt") do |line|
puts line.chomp
end
# 读成数组
lines = File.readlines("test.txt")
puts lines.inspect
# 写文件(覆盖)
File.write("test.txt", "新内容\n")
# 追加
File.open("test.txt", "a") { |f| f.puts "追加一行" }
# 文件存在性、大小、修改时间
puts File.exist?("test.txt") # => true
puts File.size("test.txt") # => 字节数
puts File.mtime("test.txt") # => 修改时间 Time 对象
# 目录操作
Dir.mkdir("backup") unless Dir.exist?("backup")
Dir.entries(".").each { |e| puts e } # 列出目录
步骤 2:CSV 与 JSON——日常数据格式
require "csv"
require "json"
# CSV 读取
csv_text = <<~CSV
name,age,city
Tom,25,Beijing
Lisa,30,Shanghai
CSV
CSV.parse(csv_text, headers: true) do |row|
puts "#{row['name']} 住在 #{row['city']}"
end
# CSV 写入
CSV.open("users.csv", "w") do |csv|
csv << ["name", "age"]
csv << ["Tom", 25]
csv << ["Lisa", 30]
end
# JSON 解析与生成
json_str = '{"name":"Tom","tags":["admin","dev"]}'
data = JSON.parse(json_str)
puts data["name"] # => Tom
puts data["tags"].inspect # => ["admin", "dev"]
hash = { name: "Lisa", scores: [90, 85] }
puts JSON.generate(hash) # => {"name":"Lisa","scores":[90,85]}
puts JSON.pretty_generate(hash) # 格式化输出