蓝色天空网mbsky.com · 知识 · 实践 · 创造Ruby · 本地阅读预览
教程 / 编程语言 / Ruby

Ruby 范围(Range)

解析 Ruby Range 对象的三大典型用途:.. 与 ... 序列生成与遍历、作为 case/触发器条件表达式、以及利用 === 执行数值与字符间隔判定。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

作为序列的范围:.. 与 ... 及遍历方法

Ruby 的范围(`Range`)用来简洁地表示从起点到终点的连续区间,在实际编码中主要承担三类职责:作为序列、作为条件以及作为间隔检测。创建序列范围使用两点运算符 `..`(闭区间,包含右端点,例如 `(1..5)` 生成 `1, 2, 3, 4, 5`)或三点运算符 `...`(左闭右开区间,排除右端点,例如 `(1...5)` 生成 `1, 2, 3, 4`),字符串同样支持如 `('a'..'d')`。

`Range` 内部仅保存起止端点引用(现代 Ruby 中整数统一为 `Integer` 类,早年称为 `Fixnum`),内存占用极小;调用 `to_a` 才会按 `succ` 规则展开为完整数组,例如 `(1..10).to_a` 与 `('bar'..'bat').to_a`(依次为 `"bar"`, `"bas"`, `"bat"`)。同时 `Range` 混入了 `Enumerable`,可直接调用 `include?`、`min`、`max`、`reject` 和 `each` 检索、过滤或遍历元素(如 `digits = 0..9` 过滤出不小于 5 的 `[5, 6, 7, 8, 9]`)。

作为条件的范围:触发器与 case 分支

在条件语句中直接书写 `/start/../end/` 会激活 Ruby 的翻转型条件(flip-flop):当某一行匹配 `/start/` 时条件转为真并持续保持,直到后续某一行匹配 `/end/` 后重新关闭,常用于单行文本流脚本中截取起止标记之间的段落。

`Range` 与 `case ... when` 语句配合尤为自然。Ruby 在匹配 `when` 分支时底层调用分支表达式的 `===` 方法,因此 `when 0..40`、`when 41..60`、`when 61..70`、`when 71..100` 可将分数直接映射为对应等级(如 `score = 70` 命中 `61..70` 返回 `"及格分数"`),代码比多层 `if/elsif` 更直观。

作为间隔的范围:=== 包含检测

除遍历与分支外,`Range` 还可用 `===` 运算符执行间隔判定,检测目标值是否落入上下界之间:`(1..10) === 5` 与 `('a'..'j') === 'c'` 均返回 `true`,而 `('a'..'j') === 'z'` 返回 `false`。需留意当使用 `...` 排除右端点时,右边界本身(如 `(1...5) === 5`)判定为 `false`;Ruby 2.6+ 起还支持无边界范围如 `(1..)` 与 `(..10)`。

离线校验 Ruby Range 闭/半开序列、Enumerable 方法、case 区间与 === 判定

python · 阅读源码
"""Offline Ruby 3.x semantic verification lab for Chapter 25 (range)."""
import json
import re

VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"


def ruby_str_succ(s: str) -> str:
    """Ruby String#succ for ASCII lowercase letters."""
    chars = list(s)
    i = len(chars) - 1
    while i >= 0:
        if chars[i] < "z":
            chars[i] = chr(ord(chars[i]) + 1)
            return "".join(chars)
        chars[i] = "a"
        i -= 1
    return "a" + "".join(chars)


def ruby_str_range(start: str, end: str, exclude_end: bool = False):
    out = []
    cur = start
    while True:
        if cur == end:
            if not exclude_end:
                out.append(cur)
            break
        out.append(cur)
        cur = ruby_str_succ(cur)
        if len(out) > 100:
            break
    return out


def case_inclusive_exclusive_sequences():
    incl = list(range(1, 5 + 1))
    excl = list(range(1, 5))
    chars = ruby_str_range("a", "d")
    words = ruby_str_range("bar", "bat")
    expected = {
        "incl_1_to_5": [1, 2, 3, 4, 5],
        "excl_1_to_5": [1, 2, 3, 4],
        "a_to_d": ["a", "b", "c", "d"],
        "bar_to_bat": ["bar", "bas", "bat"],
    }
    actual = {
        "incl_1_to_5": incl,
        "excl_1_to_5": excl,
        "a_to_d": chars,
        "bar_to_bat": words,
    }
    return {
        "name": "inclusive_exclusive_sequences",
        "summary": "核验闭区间 .. 与半开区间 ... 端点差异,以及字符串范围基于 String#succ 的序列展开",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_range_enumeration_and_reject():
    digits = list(range(0, 10))
    rejected = [i for i in digits if not (i < 5)]
    expected = {
        "include_5": True,
        "min": 0,
        "max": 9,
        "reject_lt_5": [5, 6, 7, 8, 9],
        "each_count": 10,
    }
    actual = {
        "include_5": 5 in digits,
        "min": min(digits),
        "max": max(digits),
        "reject_lt_5": rejected,
        "each_count": len(digits),
    }
    return {
        "name": "range_enumeration_and_reject",
        "summary": "核验 Range#include?、min、max、reject 与 each 遍历语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_case_and_flipflop_conditions():
    def grade(score: int) -> str:
        if 0 <= score <= 40:
            return "糟糕的分数"
        if 41 <= score <= 60:
            return "快要及格"
        if 61 <= score <= 70:
            return "及格分数"
        if 71 <= score <= 100:
            return "良好分数"
        return "错误的分数"

    lines = ["intro", "start block", "middle line", "end block", "after"]
    active = False
    captured = []
    for line in lines:
        if not active and re.search(r"start", line):
            active = True
        if active:
            captured.append(line)
            if re.search(r"end", line):
                active = False

    expected = {
        "score_70": "及格分数",
        "score_85": "良好分数",
        "score_105": "错误的分数",
        "flipflop_lines": ["start block", "middle line", "end block"],
    }
    actual = {
        "score_70": grade(70),
        "score_85": grade(85),
        "score_105": grade(105),
        "flipflop_lines": captured,
    }
    return {
        "name": "case_and_flipflop_conditions",
        "summary": "核验 Range 在 case/when 区间匹配及 /start/../end/ 触发器条件中的状态切换",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_triple_equals_interval_check():
    def range_covers(lo, hi, val, exclude_end=False):
        return (lo <= val < hi) if exclude_end else (lo <= val <= hi)

    expected = {
        "int_in_1_10": True,
        "char_c_in_a_j": True,
        "char_z_in_a_j": False,
        "excl_5_in_1_5": False,
    }
    actual = {
        "int_in_1_10": range_covers(1, 10, 5),
        "char_c_in_a_j": range_covers("a", "j", "c"),
        "char_z_in_a_j": range_covers("a", "j", "z"),
        "excl_5_in_1_5": range_covers(1, 5, 5, exclude_end=True),
    }
    return {
        "name": "triple_equals_interval_check",
        "summary": "核验 Range#=== 间隔包含检测在整型、字符与半开边界下的布尔结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_inclusive_exclusive_sequences(),
        case_range_enumeration_and_reject(),
        case_case_and_flipflop_conditions(),
        case_triple_equals_interval_check(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 4 个确定性用例全部通过,确认 .. 与 ... 端点差异、字符串 succ 展开、flip-flop 区间截取及 === 边界判定。
离线校验 Ruby Range 闭/半开序列、Enumerable 方法、case 区间与 === 判定

所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。

当前源码 SHA256:db158b98752f13d0cbd2738dba814cf0072da72b7f76ee75487b17162bba47b1

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Ruby 范围(Range)实验

所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。

ZIP SHA256:5853c27d877e4fb5b288b27ecc3e76287cc448f2f292ed842608a5a31f95fb30

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

表达式 `(1..5).to_a` 与 `(1...5).to_a` 的结果分别是什么?`(1...5) === 5` 返回什么?

展开参考解答

`(1..5).to_a` 为 `[1, 2, 3, 4, 5]`,`(1...5).to_a` 为 `[1, 2, 3, 4]`;因为 `...` 不包含上界,`(1...5) === 5` 返回 `false`。

规范与官方依据