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

Ruby 类案例

通过完整的 Customer 客户类案例,串联类变量计数、initialize 初始化、实例变量双引号插值、多对象创建及 main.rb 运行输出追踪。

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

学完这一章,你能够

设计 Customer 类与双引号变量插值

本章通过构建一个完整的 `Customer` 类来综合练习面向对象基础:除 `initialize` 构造方法外,类中声明两个核心实例方法——`display_details` 用于打印单个客户的编号、姓名与地址,`total_no_of_customers` 用于递增并输出系统累计登记的客户总数。

`display_details` 内使用 `puts "Customer id #@cust_id"` 等三条语句输出实例属性。Ruby 双引号字符串支持对实例变量(`#@var`)、类变量(`#@@var`)与全局变量(`#$var`)省略花括号的简写插值(现代风格指南通常仍推荐统一写作 `#{@cust_id}` 以提高清晰度)。在 `total_no_of_customers` 中,每次调用都会执行 `@@no_of_customers += 1` 更新类级计数器并打印最新总数。

实例化多对象与方法调用

调用 `Customer.new` 分别构造 `cust1` 与 `cust2` 两个独立对象后,使用点号运算符依次调用 `cust1.display_details()`、`cust1.total_no_of_customers()` 以及 `cust2` 的同名方法(Ruby 中无参方法调用可省略空括号)。两位客户的 `@cust_*` 实例变量彼此独立,而 `@@no_of_customers` 则在两者之间共享累加。

保存为 main.rb 并核对完整执行结果

将类定义、对象创建与方法调用整合保存到 `main.rb`,在命令行运行 `ruby main.rb`。程序先输出 `cust1` 的三行客户详情并打印 `Total number of customers: 1`,随后输出 `cust2` 的三行客户详情并将共享类变量递增打印为 `Total number of customers: 2`,共计 8 行标准输出。

离线校验 Customer 类实例变量插值、类变量共享计数与 main.rb 全量 8 行输出

python · 阅读源码
"""Offline Ruby 3.x semantic verification lab for Chapter 12 (class-case-study)."""
import json

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


class CustomerSim:
    no_of_customers = 0

    def __init__(self, cid, name, addr):
        self.cust_id = cid
        self.cust_name = name
        self.cust_addr = addr

    def display_details(self):
        return [
            f"Customer id {self.cust_id}",
            f"Customer name {self.cust_name}",
            f"Customer address {self.cust_addr}",
        ]

    def total_no_of_customers(self):
        CustomerSim.no_of_customers += 1
        return f"Total number of customers: {CustomerSim.no_of_customers}"


def case_customer_initialize_and_instance_interpolation():
    c1 = CustomerSim("1", "John", "Wisdom Apartments, Ludhiya")
    lines = c1.display_details()
    expected = {
        "lines": [
            "Customer id 1",
            "Customer name John",
            "Customer address Wisdom Apartments, Ludhiya",
        ],
        "short_ivar_interp_requires_double_quotes": True,
    }
    actual = {
        "lines": lines,
        "short_ivar_interp_requires_double_quotes": True,
    }
    return {
        "name": "customer_initialize_and_instance_interpolation",
        "summary": "校验 Customer#initialize 实例变量赋值及双引号内 #@cust_id 简写插值输出",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_class_variable_shared_counter():
    CustomerSim.no_of_customers = 0
    c1 = CustomerSim("1", "John", "Wisdom Apartments, Ludhiya")
    c2 = CustomerSim("2", "Poul", "New Empire road, Khandala")
    r1 = c1.total_no_of_customers()
    r2 = c2.total_no_of_customers()
    expected = {
        "first_call": "Total number of customers: 1",
        "second_call": "Total number of customers: 2",
        "final_counter": 2,
    }
    actual = {"first_call": r1, "second_call": r2, "final_counter": CustomerSim.no_of_customers}
    return {
        "name": "class_variable_shared_counter",
        "summary": "验证不同对象调用 total_no_of_customers 时共享递增同一类变量 @@no_of_customers",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_multi_instance_method_dispatch():
    CustomerSim.no_of_customers = 0
    c1 = CustomerSim("1", "John", "Wisdom Apartments, Ludhiya")
    c2 = CustomerSim("2", "Poul", "New Empire road, Khandala")
    expected = {
        "c1_id_line": "Customer id 1",
        "c2_id_line": "Customer id 2",
        "distinct_receivers": True,
    }
    actual = {
        "c1_id_line": c1.display_details()[0],
        "c2_id_line": c2.display_details()[0],
        "distinct_receivers": c1 is not c2,
    }
    return {
        "name": "multi_instance_method_dispatch",
        "summary": "校验点号消息分发在不同实例接收者 cust1 与 cust2 上读取各自隔离的实例变量",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_main_rb_full_stdout_trace():
    CustomerSim.no_of_customers = 0
    c1 = CustomerSim("1", "John", "Wisdom Apartments, Ludhiya")
    c2 = CustomerSim("2", "Poul", "New Empire road, Khandala")
    out = []
    out.extend(c1.display_details())
    out.append(c1.total_no_of_customers())
    out.extend(c2.display_details())
    out.append(c2.total_no_of_customers())
    expected = [
        "Customer id 1",
        "Customer name John",
        "Customer address Wisdom Apartments, Ludhiya",
        "Total number of customers: 1",
        "Customer id 2",
        "Customer name Poul",
        "Customer address New Empire road, Khandala",
        "Total number of customers: 2",
    ]
    return {
        "name": "main_rb_full_stdout_trace",
        "summary": "端到端核对完整 main.rb 示例的全部 8 行标准输出结果",
        "expected": expected,
        "actual": out,
        "passed": out == expected,
    }


def main():
    cases = [
        case_customer_initialize_and_instance_interpolation(),
        case_class_variable_shared_counter(),
        case_multi_instance_method_dispatch(),
        case_main_rb_full_stdout_trace(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器逐项核对 cust1/cust2 实例状态隔离、@@no_of_customers 跨对象递增为 1->2 以及 main.rb 全部 8 行输出完全吻合。
离线校验 Customer 类实例变量插值、类变量共享计数与 main.rb 全量 8 行输出

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

当前源码 SHA256:d9ecb9bd01dd9981f472e6911cc875fd6418299bc932defc935b101ff26cba35

下载本站示例源码

本地运行

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

下载Ruby 类案例实验

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

ZIP SHA256:0e232e2cc965add5c8a718159bef6001d6626222a86018e065b3ddcf475f1a57

常见错误与边界

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

练习与解答

如果在上述 `Customer` 案例中将计数器改为放在 `initialize` 里执行 `@@no_of_customers += 1`,与放在 `total_no_of_customers` 里相比有什么区别?

展开参考解答

放在 `initialize` 中能准确反映实际创建的客户对象总数,多次调用查询方法不会重复计数;而原案例放在 `total_no_of_customers` 里属于每次调用即自增,重复调用同一对象的该方法会导致计数虚高。

规范与官方依据