Ruby Dir 类和方法
梳理 Ruby Dir 目录流类的 11 项类方法(含通配符 glob、工作目录切换、增删目录)与 9 项实例流游标方法(read/each/pos/tell/seek/rewind/close)。
学完这一章,你能够
- 梳理 Ruby Dir 目录流类的 11 项类方法(含通配符 glob、工作目录切换、增删目录)与 9 项实例流游标方法(read/each/pos/tell/seek/rewind/close)。
Dir 类定位与通配符匹配类方法
`Dir` 类代表操作系统中的目录流(Directory Stream),提供目录遍历、通配符文件名匹配、当前工作目录切换以及目录创建与删除等核心能力。调用 `Dir.open(path) { |dir| ... }` 会在代码块结束时自动关闭目录流,避免句柄泄漏。
`Dir[pat]` 与 `Dir.glob(pat)` 支持丰富的路径通配符语法:`*` 匹配包含空串在内的任意文件名字符;`**` 递归匹配任意层级子目录;`?` 匹配单个任意字符;`[...]` 匹配方括号字符集中的任意单字符;`{a,b...}` 匹配花括号中任一候选子串。例如 `Dir["foo.*"]` 可同时匹配 `foo.c` 与 `foo.rb`,而 `Dir["foo.?"]` 仅匹配单字符后缀如 `foo.c` 和 `foo.h`。
Dir 实例方法与目录流游标控制
通过 `Dir.new(path)` 或 `Dir.open(path)` 获得 `Dir` 实例 `d` 后,可像读取文件流一样逐项推进目录条目:`d.read` 顺序返回下一个条目名并在末尾返回 `nil`;`d.each` 将每个条目交给代码块;`d.pos`/`d.tell` 读取当前流位置,配合 `d.seek(pos)` 或 `d.pos=` 可回到先前保存的位置,`d.rewind` 直接复位到首个条目,最后通过 `d.close` 释放目录流。
Ruby Dir 类方法参考表
| 序号 | 方法签名 | 作用说明 |
|---|---|---|
| 1 | Dir[pat] / Dir.glob(pat) | 按通配符模式(*、**、?、[...]、{a,b})返回匹配的文件路径数组。 |
| 2 | Dir.chdir(path) | 切换当前进程的工作目录;传入代码块时仅在块内临时生效并自动恢复。 |
| 3 | Dir.chroot(path) | 修改进程根目录(需超级用户权限,仅部分类 Unix 平台支持)。 |
| 4 | Dir.delete(path) | 删除指定的空目录,非空目录将抛出系统错误。 |
| 5 | Dir.entries(path) | 返回包含目录 path 内全部条目的数组(含 . 与 ..)。 |
| 6 | Dir.foreach(path) {|f| ...} | 逐一遍历目录中的每个条目并传给代码块执行。 |
| 7 | Dir.getwd / Dir.pwd | 返回当前工作目录的完整路径字符串。 |
| 8 | Dir.mkdir(path[, mode=0777]) | 新建目录;权限受进程 umask 约束,Windows 平台会忽略 Unix 模式位。 |
| 9 | Dir.new(path) / Dir.open(path) [{|dir| ...}] | 打开目录流对象;Dir.open 搭配代码块时会在块退出后自动关闭流。 |
| 10 | Dir.pwd | Dir.getwd 的常用别名,返回当前工作目录。 |
| 11 | Dir.rmdir / Dir.unlink / Dir.delete(path) | 三者互为别名,用于删除已清空的空目录。 |
Ruby Dir 实例方法参考表
| 序号 | 方法签名 | 作用说明 |
|---|---|---|
| 1 | d.close | 关闭目录流并释放操作系统目录句柄。 |
| 2 | d.each {|f| ...} | 遍历目录流 d 中的每一个条目并传入代码块。 |
| 3 | d.pos / d.tell | 返回目录流当前的游标位置整数。 |
| 4 | d.pos = offset | 将目录流游标移动到指定偏移位置 offset。 |
| 5 | d.pos = pos / d.seek(pos) | 跳转到由 d.pos 或 d.tell 预先记录的有效位置(或 0)。 |
| 6 | d.read | 读取并返回下一个目录项名称,到达末尾返回 nil。 |
| 7 | d.rewind | 将目录流游标重置到第一个目录项。 |
| 8 | d.seek(pos) | 设置目录流游标位置(返回目录对象本身),语义同 d.pos = pos。 |
| 9 | d.tell | d.pos 的别名,返回目录流当前读取位置。 |
离线校验 Ruby Dir 通配符 glob、目录增删与实例流 read/tell/seek/rewind
"""Offline Ruby 3.x semantic verification lab for Chapter 29 (dir-methods)."""
import fnmatch
import json
import os
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_dir_glob_patterns():
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "sub").mkdir()
files = ["foo.c", "foo.h", "foo.rb", "bar.txt", "sub/nested.rb"]
for rel in files:
(root / rel).write_text("# sample\n", encoding="utf-8")
star = sorted(p.name for p in root.glob("foo.*"))
qmark = sorted(p.name for p in root.glob("foo.?"))
bracket = sorted(p.name for p in root.glob("foo.[ch]"))
recursive = sorted(p.relative_to(root).as_posix() for p in root.glob("**/*.rb"))
# Brace alternation {c,rb}
brace = sorted(
name for name in os.listdir(root)
if fnmatch.fnmatch(name, "foo.c") or fnmatch.fnmatch(name, "foo.rb")
)
expected = {
"foo_star": ["foo.c", "foo.h", "foo.rb"],
"foo_qmark": ["foo.c", "foo.h"],
"foo_bracket": ["foo.c", "foo.h"],
"recursive_rb": ["foo.rb", "sub/nested.rb"],
"brace_c_rb": ["foo.c", "foo.rb"],
}
actual = {
"foo_star": star,
"foo_qmark": qmark,
"foo_bracket": bracket,
"recursive_rb": recursive,
"brace_c_rb": brace,
}
return {
"name": "dir_glob_patterns",
"summary": "核验 Dir[] / Dir.glob 通配符 *、**、?、[...] 与 {a,b} 展开匹配结果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dir_entries_mkdir_rmdir():
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
work = root / "demo_dir"
work.mkdir()
(work / "alpha.rb").write_text("", encoding="utf-8")
(work / "beta.rb").write_text("", encoding="utf-8")
entries = [".", ".."] + sorted(os.listdir(work))
foreach_items = [x for x in entries if x not in (".", "..")]
# Non-empty dir cannot be deleted until emptied
non_empty_error = False
try:
work.rmdir()
except OSError:
non_empty_error = True
(work / "alpha.rb").unlink()
(work / "beta.rb").unlink()
work.rmdir()
expected = {
"entries": [".", "..", "alpha.rb", "beta.rb"],
"foreach_items": ["alpha.rb", "beta.rb"],
"non_empty_rmdir_raises": True,
"empty_rmdir_succeeded": True,
}
actual = {
"entries": entries,
"foreach_items": foreach_items,
"non_empty_rmdir_raises": non_empty_error,
"empty_rmdir_succeeded": not work.exists(),
}
return {
"name": "dir_entries_mkdir_rmdir",
"summary": "核验 Dir.mkdir、Dir.entries(含 . 和 ..)、Dir.foreach 与 Dir.delete/rmdir 仅允许删空目录的规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dir_stream_pos_seek_rewind():
# Simulate Ruby Dir instance stream: read, tell/pos, seek/pos=, rewind, close
class DirStream:
def __init__(self, items):
self._items = list(items)
self._pos = 0
self.closed = False
def read(self):
if self._pos >= len(self._items):
return None
val = self._items[self._pos]
self._pos += 1
return val
def tell(self):
return self._pos
def seek(self, pos):
self._pos = pos
return self
def rewind(self):
self._pos = 0
return self
def close(self):
self.closed = True
d = DirStream([".", "..", "a.rb", "b.rb"])
first = d.read()
saved_pos = d.tell()
second = d.read()
d.seek(saved_pos)
reread_second = d.read()
d.rewind()
after_rewind = d.read()
d.close()
expected = {
"first": ".",
"saved_pos": 1,
"second": "..",
"reread_second": "..",
"after_rewind": ".",
"closed": True,
}
actual = {
"first": first,
"saved_pos": saved_pos,
"second": second,
"reread_second": reread_second,
"after_rewind": after_rewind,
"closed": d.closed,
}
return {
"name": "dir_stream_pos_seek_rewind",
"summary": "核验 Dir 实例流方法 read、pos/tell、seek/pos=、rewind 与 close 的游标状态迁移",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_dir_glob_patterns(),
case_dir_entries_mkdir_rmdir(),
case_dir_stream_pos_seek_rewind(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 3 个确定性用例全部通过,验证 *、**、?、[...]、{a,b} 匹配、非空目录删失败拦截及目录流游标回退。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
当前源码 SHA256:00f65fd7e6469352a60cb9b5fb53d1b4dae69e4a1ab6eac3699f7fe8a34fbabe
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
ZIP SHA256:554d236ac8a5045815e39436cc8f2103f1d5c9708abf4b1071bbf5bcbf57901d
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
调用 `Dir.delete("project")` 删除非空目录时会发生什么?如果确实要递归删除非空目录,Ruby 标准库通常配合哪个模块?
展开参考解答
`Dir.delete` 只能删除空目录,遇到非空目录会抛出 `Errno::ENOTEMPTY` 异常;递归删除非空目录应引入标准库 `fileutils` 并使用 `FileUtils.rm_rf`。