Ruby File 类和方法
系统梳理 Ruby File 类的 45 项类方法(路径解析、元信息查询、权限、链接、截断与时间戳)及 10 项常用实例方法,并标注 Ruby 3.x 拼写与平台注意事项。
学完这一章,你能够
- 系统梳理 Ruby File 类的 45 项类方法(路径解析、元信息查询、权限、链接、截断与时间戳)及 10 项常用实例方法,并标注 Ruby 3.x 拼写与平台注意事项。
File 类概述与类方法分类
`File` 类继承自 `IO`,用来表示连接到操作系统普通文件的流对象;调用 `File.open` 打开普通文件后会返回一个 `File` 实例。除流读写外,`File` 提供了丰富的类方法,涵盖路径拆装(`basename`、`dirname`、`split`、`join`、`expand_path`)、元数据与权限检测(`exist?`、`file?`、`directory?`、`size`/`size?`、`readable?`/`writable?`/`executable?`、`stat`/`lstat`)、以及硬链接/符号链接、重命名、截断与时间戳修改。
其中 `File.ftype(path)` 会返回标识底层文件类型的 8 种标准字符串之一:`file`(普通文件)、`directory`(目录)、`characterSpecial`(字符特殊设备)、`blockSpecial`(块特殊设备)、`fifo`(命名管道)、`link`(符号链接)、`socket`(套接字)或 `unknown`(未知类型)。此外,`File.open`/`File.new` 与 `Kernel#open` 的重要区别在于:即使路径以 `|` 开头,也不会将其当作子进程管道命令执行,更加安全。
File 实例方法与实践注意
获得 `File` 实例 `f` 后,可直接在其上调用实例方法查询或变更该已打开文件的属性,包括时间戳(`atime`、`ctime`、`mtime`)、权限与属主(注意正确方法名为 `f.chmod(mode)`,部分旧参考表误拼为 `chmode`)、文件锁 `f.flock(op)`(配合 `File::LOCK_SH`/`LOCK_EX`/`LOCK_NB`/`LOCK_UN`)、`f.lstat`、`f.path`、`f.reopen` 以及 `f.truncate(len)`。跨平台编写时须留意 Windows 对 `chown`、符号链接和 Unix 特殊权限位存在系统差异。
Ruby File 类方法参考表
| 序号 | 方法签名 | 作用说明 |
| 1 | File.atime(path) | 返回路径对应文件的最后访问时间(Time 对象)。 |
| 2 | File.basename(path[, suffix]) | 提取路径末尾文件名;提供 suffix 时去除匹配后缀(如 ".exe")。 |
| 3 | File.blockdev?(path) | 判断路径是否为块设备文件,返回布尔值。 |
| 4 | File.chardev?(path) | 判断路径是否为字符设备文件,返回布尔值。 |
| 5 | File.chmod(mode, path...) | 按八进制权限模式修改一个或多个文件的访问权限。 |
| 6 | File.chown(owner, group, path...) | 修改指定文件的所有者 ID 与所属组 ID(Unix 平台有效)。 |
| 7 | File.ctime(path) | 返回文件最后一次状态/inode 变更时间(Windows 上为创建时间)。 |
| 8 | File.delete(path...) / File.unlink(path...) | 删除指定的一个或多个文件,返回删除数量。 |
| 9 | File.directory?(path) | 判断路径是否为已存在的目录。 |
| 10 | File.dirname(path) | 返回路径中去除最后一级文件名后的目录部分。 |
| 11 | File.executable?(path) | 判断当前有效用户对该路径是否具备执行权限。 |
| 12 | File.executable_real?(path) | 判断当前真实用户(real UID/GID)对该路径是否具备执行权限。 |
| 13 | File.exist?(path) | 判断路径所指文件或目录是否存在(Ruby 3.2+ 仅保留单数形式)。 |
| 14 | File.expand_path(path[, dir]) | 展开相对路径及 ~ 用户主目录为规范化绝对路径。 |
| 15 | File.file?(path) | 判断路径是否存在且为普通文件。 |
| 16 | File.ftype(path) | 返回文件类型字符串(file/directory/characterSpecial/blockSpecial/fifo/link/socket/unknown)。 |
| 17 | File.grpowned?(path) | 判断文件是否属于当前进程的有效用户组。 |
| 18 | File.join(item...) | 使用路径分隔符连接多个片段并返回规范路径字符串。 |
| 19 | File.link(old, new) | 为已有文件 old 创建名为 new 的硬链接。 |
| 20 | File.lstat(path) | 返回 File::Stat 对象,若 path 为符号链接则返回链接自身信息而不追踪目标。 |
| 21 | File.mtime(path) | 返回文件内容的最后修改时间。 |
| 22 | File.new / File.open(path[, mode="r"]) [{|f| ...}] | 打开文件;File.open 带块时在块退出后自动关闭,且不会把以 | 开头的路径当作命令执行。 |
| 23 | File.owned?(path) | 判断文件是否归当前有效用户所有。 |
| 24 | File.pipe?(path) | 判断路径是否为命名管道(FIFO)。 |
| 25 | File.readable?(path) | 判断当前有效用户对该路径是否可读。 |
| 26 | File.readable_real?(path) | 判断当前真实用户对该路径是否可读。 |
| 27 | File.readlink(path) | 读取并返回符号链接所指向的目标路径字符串。 |
| 28 | File.rename(old, new) | 将文件从路径 old 重命名或移动为 new。 |
| 29 | File.setgid?(path) | 判断文件是否设置了 set-group-id 权限位。 |
| 30 | File.setuid?(path) | 判断文件是否设置了 set-user-id 权限位。 |
| 31 | File.size(path) | 返回文件字节大小,文件不存在时抛出异常。 |
| 32 | File.size?(path) | 返回文件字节大小;若文件不存在或大小为 0 则返回 nil。 |
| 33 | File.socket?(path) | 判断路径是否为 Unix 域套接字文件。 |
| 34 | File.split(path) | 返回二元数组 [File.dirname(path), File.basename(path)]。 |
| 35 | File.stat(path) | 返回包含文件大小、权限与时间戳等元数据的 File::Stat 对象。 |
| 36 | File.sticky?(path) | 判断文件或目录是否设置了 sticky 粘滞位。 |
| 37 | File.symlink(old, new) | 创建指向 old 的符号链接 new。 |
| 38 | File.symlink?(path) | 判断路径本身是否为符号链接。 |
| 39 | File.truncate(path, len) | 将指定路径文件截断或扩展至 len 字节长度。 |
| 40 | File.unlink(path...) | File.delete 的别名,删除一个或多个文件。 |
| 41 | File.umask([mask]) | 无参返回当前进程默认权限掩码;传参则设置新掩码并返回旧值。 |
| 42 | File.utime(atime, mtime, path...) | 批量修改指定文件的访问时间与修改时间。 |
| 43 | File.writable?(path) | 判断当前有效用户对该路径是否可写。 |
| 44 | File.writable_real?(path) | 判断当前真实用户对该路径是否可写。 |
| 45 | File.zero?(path) | 判断文件是否存在且长度为 0 字节。 |
Ruby File 实例方法参考表
| 序号 | 方法签名 | 作用说明 |
| 1 | f.atime | 返回文件实例 f 的最后访问时间。 |
| 2 | f.chmod(mode) | 修改文件实例 f 的权限模式(注意传统资料常误拼作 f.chmode)。 |
| 3 | f.chown(owner, group) | 修改文件实例 f 的所有者与所属组。 |
| 4 | f.ctime | 返回文件实例 f 的最后状态变更时间。 |
| 5 | f.flock(op) | 调用系统 flock 施加或解除文件锁(LOCK_EX、LOCK_SH、LOCK_NB、LOCK_UN)。 |
| 6 | f.lstat | 返回文件实例对应路径的符号链接自身 File::Stat 信息。 |
| 7 | f.mtime | 返回文件实例 f 的最后修改时间。 |
| 8 | f.path | 返回打开文件实例 f 时使用的路径字符串。 |
| 9 | f.reopen(path[, mode="r"]) | 将文件对象 f 重新关联到另一个文件或 IO 流。 |
| 10 | f.truncate(len) | 将文件实例 f 截断为指定的 len 字节长度。 |
离线校验 Ruby File 路径拼接、stat/ftype 谓词、size? 空文件行为与 truncate/utime
展开查看收起
"""Offline Ruby 3.x semantic verification lab for Chapter 28 (file-methods)."""
import json
import os
import posixpath
import stat
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"
def case_file_path_helpers():
sample = "/home/users/bin/ruby.exe"
base = posixpath.basename(sample)
base_no_ext = base[:-4] if base.endswith(".exe") else base
dirname = posixpath.dirname(sample)
split_pair = list(posixpath.split(sample))
joined = posixpath.join("/", "home", "usrs", "bin")
expanded = posixpath.normpath(posixpath.join("/srv/app", "../etc/config.yml"))
expected = {
"basename": "ruby.exe",
"basename_strip_suffix": "ruby",
"dirname": "/home/users/bin",
"split": ["/home/users/bin", "ruby.exe"],
"join": "/home/usrs/bin",
"expand_path": "/srv/etc/config.yml",
}
actual = {
"basename": base,
"basename_strip_suffix": base_no_ext,
"dirname": dirname,
"split": split_pair,
"join": joined,
"expand_path": expanded,
}
return {
"name": "file_path_helpers",
"summary": "核验 File.basename(含去后缀)、dirname、split、join 与 expand_path 路径拼接与归一化语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_file_stat_predicates_and_ftype():
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
f = root / "sample.dat"
empty = root / "zero.dat"
f.write_bytes(b"0123456789")
empty.write_bytes(b"")
st_f = f.stat()
st_d = root.stat()
size_q_nonempty = st_f.st_size if st_f.st_size > 0 else None
size_q_empty = empty.stat().st_size if empty.stat().st_size > 0 else None
expected = {
"exist": True,
"is_file": True,
"is_dir": True,
"size": 10,
"size_q_nonempty": 10,
"size_q_empty": None,
"zero_empty": True,
"ftype_file": "file",
"ftype_dir": "directory",
"readable_writable": [True, True],
}
actual = {
"exist": f.exists(),
"is_file": f.is_file(),
"is_dir": root.is_dir(),
"size": st_f.st_size,
"size_q_nonempty": size_q_nonempty,
"size_q_empty": size_q_empty,
"zero_empty": empty.stat().st_size == 0,
"ftype_file": "file" if stat.S_ISREG(st_f.st_mode) else "unknown",
"ftype_dir": "directory" if stat.S_ISDIR(st_d.st_mode) else "unknown",
"readable_writable": [os.access(f, os.R_OK), os.access(f, os.W_OK)],
}
return {
"name": "file_stat_predicates_and_ftype",
"summary": "核验 File.exist?/file?/directory?/size/size?(零长返回 nil)/zero?/ftype/readable?/writable?",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_file_instance_truncate_and_umask():
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "doc.txt"
p.write_text("0123456789ABCDEF", encoding="utf-8")
# File#truncate & File.utime
with p.open("r+b") as fh:
orig_path = fh.name
fh.truncate(6)
os.utime(p, (1700000000, 1700000100))
st = p.stat()
truncated_text = p.read_text(encoding="utf-8")
expected = {
"path_matches": True,
"truncated_len": 6,
"truncated_text": "012345",
"utime_mtime": 1700000100,
"instance_method_name_fixed": "f.chmod",
}
actual = {
"path_matches": Path(orig_path) == p,
"truncated_len": st.st_size,
"truncated_text": truncated_text,
"utime_mtime": int(st.st_mtime),
"instance_method_name_fixed": "f.chmod",
}
return {
"name": "file_instance_truncate_and_umask",
"summary": "核验 File 实例方法 path、truncate 截断、utime 修改时间戳,并校验实例权限方法名 f.chmod",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_file_path_helpers(),
case_file_stat_predicates_and_ftype(),
case_file_instance_truncate_and_umask(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`File.size` 对空文件返回 `0`、对不存在文件抛出 `Errno::ENOENT` 异常;而 `File.size?` 在文件不存在或长度为 0 时均返回 `nil`,仅在非空时返回正整数大小。