蓝色天空.知识 · 实践 · 创造
我的收藏
Ruby 教程目录 45章
Ruby / LEARN BY DOING

Ruby 类和对象

阐述面向对象四大支柱与类蓝图概念,详解 Ruby 类定义语法、四种作用域变量、new 与 initialize 对象构造机制以及类内实例方法定义与调用。

学完这一章,你能够

  • 阐述面向对象四大支柱与类蓝图概念,详解 Ruby 类定义语法、四种作用域变量、new 与 initialize 对象构造机制以及类内实例方法定义与调用。

面向对象概念与类定义语法

作为纯粹的面向对象语言,Ruby 完整支持数据封装、数据抽象、多态性与继承四大核心特性(更深入的继承、重写与访问控制将在后续面向对象专题展开)。

类是创建具体对象的蓝图,将数据属性与操作行为组织在一起。以交通工具 `Vehicle` 概念蓝图为例,轮子数、马力、油箱类型与容量区分不同个体,而加速、驾驶、停车等操作定义其行为;赋予不同属性值后即可构造出 3 轮 1000 马力 100 升油箱的飞机实例,或 4 轮 200 马力 25 升油箱的汽车实例。

在 Ruby 中定义类使用 `class 类名 ... end` 语法结构,类名属于常量,必须以大写字母开头(通常采用大驼峰 `CamelCase`,如 `class Customer ... end`),所有属性初始化逻辑与成员方法均写在 `class` 与 `end` 之间。

类中的四类变量与对象构造(new / initialize)

在类与对象开发中需清晰区分四类变量:局部变量以小写字母或 `_` 开头,仅在当前方法/块内有效;实例变量以 `@` 开头,归属于具体对象实例并可在该实例的各方法间共享;类变量以 `@@` 开头(如 `@@no_of_customers = 0`),归属于类并在所有实例及继承链中共享;全局变量以 `$` 开头,跨类全局可见但因易引发耦合应尽量避免。

创建类的实例需调用类方法 `new`(Ruby 核心库为 `Class` 预定义),写作 `cust1 = Customer.new`(语法上允许点号后有空格但现代规范推荐紧贴写作 `Customer.new`)。

当创建对象需要传入初始参数时,应在类中定义特殊实例方法 `initialize`:`Customer.new("1", "John", "Wisdom Apartments, Ludhiya")` 会先分配新对象内存,随后自动把实参转发给 `initialize(id, name, addr)`,在方法体内将局部参数赋值给实例变量 `@cust_id`、`@cust_name` 与 `@cust_addr` 完成对象状态初始化。

类成员方法与案例衔接

Ruby 中类内的成员函数称为方法,使用 `def 方法名 ... end` 定义,方法名约定以小写字母开头并使用下划线风格(`snake_case`)。例如在 `class Sample` 中定义 `def hello; puts "Hello Ruby!"; end`,通过 `object = Sample.new` 创建实例并调用 `object.hello` 后,控制台将输出 `Hello Ruby!`。

掌握类定义、变量前缀、`initialize` 构造与方法调用后,下一章《Ruby 类案例》将把这些要素整合成完整的 `Customer` 可运行实例。

离线校验类蓝图、四类变量前缀、new/initialize 构造与实例方法调用

含完整源码 · 121 行
展开查看收起
python
"""Offline Ruby 3.x semantic verification lab for Chapter 11 (class)."""
import json

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


def case_class_blueprint_and_ruby_class_syntax():
    airplane = {"wheels": 3, "horsepower": 1000, "fuel_capacity_l": 100}
    car = {"wheels": 4, "horsepower": 200, "fuel_capacity_l": 25}
    class_name = "Customer"
    expected = {
        "camel_case_constant": True,
        "airplane_hp": 1000,
        "car_wheels": 4,
        "oop_pillars": 4,
    }
    actual = {
        "camel_case_constant": class_name[0].isupper() and class_name.isalnum(),
        "airplane_hp": airplane["horsepower"],
        "car_wheels": car["wheels"],
        "oop_pillars": len(["encapsulation", "abstraction", "polymorphism", "inheritance"]),
    }
    return {
        "name": "class_blueprint_and_ruby_class_syntax",
        "summary": "验证类蓝图与多实例属性区分、OOP 四大特性及 Ruby 类名首字母大写的常量命名规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_four_variable_scopes_in_class():
    def classify_var(name):
        if name.startswith("@@"):
            return "class_variable"
        if name.startswith("@"):
            return "instance_variable"
        if name.startswith("$"):
            return "global_variable"
        if name[0].islower() or name.startswith("_"):
            return "local_variable"
        return "constant"

    expected = {
        "id": "local_variable",
        "@cust_id": "instance_variable",
        "@@no_of_customers": "class_variable",
        "$global_cfg": "global_variable",
    }
    actual = {k: classify_var(k) for k in expected}
    return {
        "name": "four_variable_scopes_in_class",
        "summary": "校验 Ruby 类语境下局部变量、@实例变量、@@类变量与 $全局变量的词法前缀识别规则",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_new_and_initialize_object_construction():
    class Customer:
        no_of_customers = 0

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

    c1 = Customer("1", "John", "Wisdom Apartments, Ludhiya")
    c2 = Customer("2", "Poul", "New Empire road, Khandala")
    expected = {
        "c1_name": "John",
        "c2_name": "Poul",
        "isolated_instance_state": True,
        "shared_class_var": 0,
    }
    actual = {
        "c1_name": c1.cust_name,
        "c2_name": c2.cust_name,
        "isolated_instance_state": c1.cust_id != c2.cust_id,
        "shared_class_var": Customer.no_of_customers,
    }
    return {
        "name": "new_and_initialize_object_construction",
        "summary": "模拟 Customer.new 触发 initialize 并将局部参数绑定到独立对象实例变量 @cust_*",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_instance_method_definition_and_invocation():
    class Sample:
        def hello(self):
            return "Hello Ruby!"

    obj = Sample()
    expected = {"method_lowercase": True, "output": "Hello Ruby!"}
    actual = {"method_lowercase": "hello"[0].islower(), "output": obj.hello()}
    return {
        "name": "instance_method_definition_and_invocation",
        "summary": "验证类内 def 定义小写方法名、Sample.new 实例化及点号调用 object.hello 输出结果",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_class_blueprint_and_ruby_class_syntax(),
        case_four_variable_scopes_in_class(),
        case_new_and_initialize_object_construction(),
        case_instance_method_definition_and_invocation(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
离线验证器确认 OOP 特性与大驼峰类名规则、四种变量前缀分类、多实例隔离与类变量共享及 Sample#hello 调用输出全部通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a2440.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Ruby

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2440.zip

下载课程关联工程包:Ruby

课程关联工程包(登记关联45章) · 含当前章节或实例 · mbskycom202612a2434.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

`Class#new` 是 Ruby 内置的构造入口,它会先调用 `allocate` 分配未初始化对象,再自动把收到的全部参数转发给该对象的私有方法 `initialize`,最后返回初始化完成的新对象。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习