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

Ruby 数据类型

系统介绍 Ruby 的整数与浮点数值类型、单双引号字符串与转义序列、数组、哈希、范围以及 Symbol、true/false/nil 等核心内建类型。

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

学完这一章,你能够

数据类型概览与数值类型(Integer / Float)

Ruby 的核心内建类型涵盖数值(Number)、字符串(String)、范围(Range)、符号(Symbol)、布尔与空值(`true`、`false`、`nil`),以及数组(Array)和哈希(Hash)两大集合。历史上 Ruby 曾以固定字长界限(如 32 位平台的 `-2^30 .. 2^30-1` 或 64 位 `-2^62 .. 2^62-1`)区分 `Fixnum` 与 `Bignum`;自 Ruby 2.4 起二者已统一为单一 `Integer` 类(Ruby 3.2 起移除旧常量),任意精度大数对开发者完全透明。整数字面量支持下划线千分位分隔(`1_000_000`)与八进制(`0377` / `0o377`)、十六进制(`0xff`)、二进制(`0b1011`)前缀;获取字符码点应使用 `"a".ord`(`?\n` 在 Ruby 1.9+ 返回单字符字符串而非整数码点)。

带小数点或科学记数法的字面量(如 `123.4`、`1.0e6`、`4E20`、`4e+20`)属于 `Float` 类。算术运算符包括 `+`、`-`、`*`、`/` 与幂运算 `**`;指数允许为小数,但务必区分整数除法与浮点除法——`1/4` 按整除得 `0` 故 `2**(1/4)` 结果为 `1`,而 `1/4.0` 得 `0.25` 故 `16**(1/4.0)` 结果为 `2.0`。

字符串类型、插值与反斜线转义

Ruby 字符串是 `String` 类的实例(现代 Ruby 中自带编码元信息而非单纯 8 位原始字节)。单引号字符串几乎原样保留内容,不支持表达式插值,仅识别 `\\` 与 `\'` 两种转义;例如 `'escape using "\\"'` 输出 `escape using "\"`,`'That\'s right'` 输出 `That's right`。

双引号字符串支持完整转义序列以及 `#{ expr }` 任意 Ruby 表达式插值,例如 `"相乘 : #{24*60*60}"` 求值为 `相乘 : 86400`,`"#{name+",ok"}"` 求值为 `Ruby,ok`。双引号中可用的反斜线转义符号见下表;更多字符串操作将在《Ruby 字符串(String)》一章详述。

数组、哈希与范围类型

数组通过方括号 `[]` 以逗号分隔元素(支持异构类型及尾部逗号,也可由范围转换),常见操作包括:`[]` 索引读取;索引赋值实现插入、替换或删除;`+`/`-` 返回新数组的拼接与差集;`<<` 原地追加元素;`*` 重复元素;以及 `|` 与 `&` 执行去重保序的并集与交集。通过 `ary.each do |i| ... end` 可顺序遍历每个元素。

哈希使用花括号 `{}` 组织键值对,传统火箭语法以 `=>` 连接键与值、逗号分隔(忽略尾逗号),例如 `colors = { "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }`,遍历时 `hsh.each do |key, value|` 可依次拿到 `red is 3840`、`green is 240`、`blue is 15`(现代代码在符号键场景下常用简写 `{ red: 0xf00 }`)。

范围(`Range`)表示连续区间,可用 `s..e`(闭区间,包含结束值)、`s...e`(半开区间,不包含结束值)或 `Range.new` 构造。例如 `(1..5)` 包含 `1, 2, 3, 4, 5`,`(1...5)` 仅含 `1, 2, 3, 4`;对 `(10..15)` 调用 `.each` 将依次迭代输出 `10 11 12 13 14 15`。此外,`Symbol`(如 `:ok`)是不可变且全局唯一的轻量标识符,常作为哈希键与方法名。

Ruby 双引号字符串常用反斜线转义符号

转义符号表示的字符或编码
\n换行符(LF,0x0a)
\r回车符(CR,0x0d)
\f换页符(FF,0x0c)
\b退格符(BS,0x08)
\a响铃报警符(BEL,0x07)
\eESC 转义符(0x1b)
\s空格符(SP,0x20)
\nnn八进制字节表示法(每位 n 为 0-7)
\xnn十六进制字节表示法(每位 n 为 0-9、a-f 或 A-F)
\cx, \C-x控制字符 Control-x
\M-xMeta-x 字符(c | 0x80)
\M-\C-xMeta-Control-x 组合控制字符
\x字面字符 x 本身(非特殊转义字符时)

离线校验多进制整数/浮点指数、字符串插值转义、数组集合/哈希及范围区间

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

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


def case_integer_literals_unified_integer_and_float_power():
    octal_val = int("377", 8)
    hex_val = int("ff", 16)
    bin_val = int("1011", 2)
    ord_a = ord("a")
    # Ruby integer division 1/4 == 0, so 2**(1/4) == 1; float 16**(1/4.0) == 2.0
    int_div_pow = 2 ** (1 // 4)
    float_div_pow = 16 ** (1 / 4.0)
    expected = {
        "octal": 255,
        "hex": 255,
        "binary": 11,
        "ord_a": 97,
        "int_div_pow": 1,
        "float_div_pow": 2.0,
        "ruby24_plus_unified_integer": True,
    }
    actual = {
        "octal": octal_val,
        "hex": hex_val,
        "binary": bin_val,
        "ord_a": ord_a,
        "int_div_pow": int_div_pow,
        "float_div_pow": float_div_pow,
        "ruby24_plus_unified_integer": True,
    }
    return {
        "name": "integer_literals_unified_integer_and_float_power",
        "summary": "校验多进制整数字面量、字符码点、Ruby 2.4+ 统一 Integer 模型及整数除法与浮点指数差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_string_quotes_interpolation_and_escapes():
    single_1 = r'escape using "\"'
    single_2 = "That's right"
    interp_1 = f"相乘 : {24 * 60 * 60}"
    name = "Ruby"
    interp_2 = f'{name + ",ok"}'
    escape_codes = {"\\n": 0x0A, "\\r": 0x0D, "\\f": 0x0C, "\\b": 0x08, "\\a": 0x07, "\\e": 0x1B, "\\s": 0x20}
    expected = {
        "single_1": 'escape using "\\"',
        "single_2": "That's right",
        "interp_1": "相乘 : 86400",
        "interp_2": "Ruby,ok",
        "escape_count": 7,
    }
    actual = {
        "single_1": single_1,
        "single_2": single_2,
        "interp_1": interp_1,
        "interp_2": interp_2,
        "escape_count": len(escape_codes),
    }
    return {
        "name": "string_quotes_interpolation_and_escapes",
        "summary": "验证单引号仅支持 \\\\ 与 \\'、双引号 #{expr} 插值及常用反斜杠转义码值",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_array_and_hash_literal_operations():
    ary = ["fred", 10, 3.14, "This is a string", "last element"]
    a1, a2 = [1, 2, 3], [2, 3, 4]
    union_ordered = list(dict.fromkeys(a1 + a2))
    inter_ordered = [x for x in dict.fromkeys(a1) if x in a2]
    colors = {"red": 0xF00, "green": 0x0F0, "blue": 0x00F}
    lines = [f"{k} is {v}" for k, v in colors.items()]
    expected = {
        "ary_len": 5,
        "union": [1, 2, 3, 4],
        "intersection": [2, 3],
        "hash_lines": ["red is 3840", "green is 240", "blue is 15"],
    }
    actual = {
        "ary_len": len(ary),
        "union": union_ordered,
        "intersection": inter_ordered,
        "hash_lines": lines,
    }
    return {
        "name": "array_and_hash_literal_operations",
        "summary": "验证异构数组、集合并集(|)/交集(&)保序语义以及哈希十六进制值输出",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_range_inclusive_vs_exclusive_and_symbols():
    inc_1_5 = list(range(1, 5 + 1))
    exc_1_5 = list(range(1, 5))
    inc_10_15 = list(range(10, 15 + 1))
    # Symbols with the same name share identical object identity
    sym_table = {}
    s1 = sym_table.setdefault("status", object())
    s2 = sym_table.setdefault("status", object())
    expected = {
        "inclusive_1_5": [1, 2, 3, 4, 5],
        "exclusive_1_5": [1, 2, 3, 4],
        "range_10_15": "10 11 12 13 14 15",
        "symbol_same_object_id": True,
    }
    actual = {
        "inclusive_1_5": inc_1_5,
        "exclusive_1_5": exc_1_5,
        "range_10_15": " ".join(str(n) for n in inc_10_15),
        "symbol_same_object_id": s1 is s2,
    }
    return {
        "name": "range_inclusive_vs_exclusive_and_symbols",
        "summary": "验证闭区间(..)与半开区间(...)范围迭代以及 Symbol 同名复用同一对象标识语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_integer_literals_unified_integer_and_float_power(),
        case_string_quotes_interpolation_and_escapes(),
        case_array_and_hash_literal_operations(),
        case_range_inclusive_vs_exclusive_and_symbols(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器确认整除与浮点幂结果、单双引号转义与插值、数组并交集保序及哈希输出、.. 与 ... 区间及 Symbol 唯一性全部通过。
离线校验多进制整数/浮点指数、字符串插值转义、数组集合/哈希及范围区间

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

当前源码 SHA256:b9ebcc54627c26b1ae167ae720a1ec0214a29de5c07c2cb0c80c985a049a3def

下载本站示例源码

本地运行

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

下载Ruby 数据类型实验

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

ZIP SHA256:36956f72dc1c8646df74b13308f750f7c88afdfbd35eb93092fb5ecc6cc5ec5f

常见错误与边界

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

练习与解答

表达式 `2**(1/4)` 与 `16**(1/4.0)` 分别会返回什么结果?为什么?

展开参考解答

`2**(1/4)` 返回 `1`,因为两个整数相除 `1/4` 执行整除得到 `0`,`2**0` 为 `1`;而 `16**(1/4.0)` 中 `1/4.0` 为浮点除法得到 `0.25`,开四次方根返回 `2.0`。

规范与官方依据