Ruby 类案例
Ruby 类案例中文讲解
Ruby 的类和对象是其面向对象编程的核心,适合创建结构化、可复用的代码。本文通过几个实用案例,详细讲解如何使用 Ruby 定义类、创建对象、实现继承和模块,以及处理中文相关内容。案例基于 Ruby 3.4.x(截至 2025 年 8 月的最新稳定版),适合初学者和有一定基础的开发者。每个案例都包含代码、说明和中文处理注意事项。
1. 案例 1:学生信息管理
这个案例展示如何定义一个简单的 Student
类,管理学生的姓名、年龄和成绩,并支持中文输入输出。
encoding: UTF-8
class Student
attr_accessor :name, :age, :grade # 定义读写访问器
def initialize(name, age, grade)
@name = name
@age = age
@grade = grade
end
def introduce
“学生姓名:#{@name},年龄:#{@age}岁,成绩:#{@grade}”
end
def update_grade(new_grade)
@grade = new_grade
“更新成绩为:#{@grade}”
end
end
测试代码
student = Student.new(“小明”, 18, “A”)
puts student.introduce # 输出: 学生姓名:小明,年龄:18岁,成绩:A
puts student.update_grade(“A+”) # 输出: 更新成绩为:A+
讲解:
- 类定义:
Student
类使用attr_accessor
自动生成name
、age
和grade
的 getter 和 setter 方法。 - 构造函数:
initialize
初始化学生的属性。 - 方法:
introduce
返回学生的介绍信息。update_grade
更新成绩并返回提示。- 中文处理:
- 文件开头声明
# encoding: UTF-8
,确保中文字符串正确处理。 - 确保终端支持 UTF-8(Windows 用户运行
chcp 65001
)。 - 运行:
ruby student.rb
注意事项:
- 保存文件为 UTF-8 编码(无 BOM)。
- 若使用中文姓名,确保终端和文件编码一致,避免乱码。
2. 案例 2:图书管理系统(继承与类变量)
这个案例展示如何使用继承和类变量管理图书信息,记录图书总数,并支持中文书名。
encoding: UTF-8
class Book
@@total_books = 0 # 类变量,记录图书总数
def initialize(title)
@title = title
@@total_books += 1
end
def details
“书名:#{@title}”
end
def self.total_books
“当前图书总数:#{@@total_books}”
end
end
class EBook < Book
def initialize(title, format)
super(title) # 调用父类构造函数
@format = format
end
def details
“#{super},格式:#{@format}”
end
end
测试代码
book = Book.new(“Ruby 编程”)
ebook = EBook.new(“Python 入门”, “PDF”)
puts book.details # 输出: 书名:Ruby 编程
puts ebook.details # 输出: 书名:Python 入门,格式:PDF
puts Book.total_books # 输出: 当前图书总数:2
讲解:
- 类变量:
@@total_books
跟踪所有图书对象的数量,共享于Book
和其子类。 - 继承:
EBook
继承Book
,通过super
调用父类的initialize
和details
方法。 - 类方法:
self.total_books
访问类变量,返回总数。 - 中文处理:
- 使用中文书名(如 “Ruby 编程”),需声明
# encoding: UTF-8
。 - 方法输出包含中文,确保终端编码为 UTF-8。
- 运行:
ruby library.rb
注意事项:
- 类变量在所有子类中共享,修改需谨慎。
- Windows 用户若遇到乱码,检查终端编码或使用 PowerShell。
3. 案例 3:员工管理(模块混入)
这个案例展示如何使用模块(Mixin)为类添加功能,管理员工信息并支持中文问候语。
encoding: UTF-8
module Greetable
def greet
“你好,我是#{@name}!”
end
end
class Employee
include Greetable
attr_accessor :name, :department
def initialize(name, department)
@name = name
@department = department
end
def work
“#{@name} 在 #{@department} 部门工作”
end
end
测试代码
employee = Employee.new(“小红”, “技术部”)
puts employee.greet # 输出: 你好,我是小红!
puts employee.work # 输出: 小红 在 技术部 部门工作
讲解:
- 模块:
Greetable
定义通用方法greet
,通过include
混入Employee
类。 - 类定义:
Employee
使用attr_accessor
定义name
和department
。 - 中文处理:
- 中文方法输出(如 “你好”)依赖 UTF-8 编码。
- 确保脚本文件保存为 UTF-8(无 BOM)。
- 运行:
ruby employee.rb
注意事项:
- 模块适合复用代码,避免重复定义。
- 中文字符串操作(如插值
#{@name}
)需确保编码一致。
4. 案例 4:中文文本处理器(正则与文件操作)
这个案例展示如何使用类处理中文文本文件,统计中文字符并保存结果。
encoding: UTF-8
class TextProcessor
def initialize(file_path)
@file_path = file_path
@content = File.read(file_path, encoding: “UTF-8”)
end
def count_chinese_chars
chinese = @content.scan(/\p{Han}/)
“文件中包含 #{chinese.length} 个中文字符”
end
def save_summary(output_file)
summary = “分析结果:#{count_chinese_chars}”
File.write(output_file, summary, encoding: “UTF-8”)
“已保存到 #{output_file}”
end
end
测试代码
processor = TextProcessor.new(“input.txt”)
puts processor.count_chinese_chars
puts processor.save_summary(“summary.txt”)
讲解:
- 类功能:
TextProcessor
读取文本文件,统计中文字符(使用正则\p{Han}
),并保存结果。 - 文件操作:使用
File.read
和File.write
,显式指定encoding: "UTF-8"
。 - 中文处理:
- 正则表达式
\p{Han}
匹配 Unicode 中的汉字。 - 输入文件
input.txt
需为 UTF-8 编码,内容示例:你好,世界!Ruby 很棒!
- 输出文件
summary.txt
包含中文分析结果。 - 运行:
ruby text_processor.rb
注意事项:
- 确保输入文件存在且为 UTF-8 编码。
- Windows 用户运行前设置:
chcp 65001
- 若处理 GBK 文件,修改为:
File.read(file_path, encoding: "GBK").encode("UTF-8")
5. 中文相关注意事项
- 编码声明:
- 每个案例都在文件开头添加
# encoding: UTF-8
,确保中文字符串正确处理。 - Windows 用户若需 GBK(如旧系统),可改为
# encoding: GBK
。
- 终端编码:
- Windows:CMD 默认 GBK,可能导致乱码,运行:
bash chcp 65001 set RUBYOPT=-EUTF-8
- Linux/macOS:默认 UTF-8,检查:
bash echo $LANG # 应为 zh_CN.UTF-8
- 文件编码:
- 保存脚本为 UTF-8(无 BOM),使用 VS Code 或 Notepad++。
- 输入/输出文件需与脚本编码一致。
- 中文方法名(不推荐):
# encoding: UTF-8
class Person
def 问好
"你好!"
end
end
- 虽然合法,但建议使用英文方法名以提高代码可读性和兼容性。
6. 常见问题与解决
- 中文乱码:
- 原因:文件或终端编码不匹配。
- 解决:
- 确保
# encoding: UTF-8
。 - 检查终端编码(Windows 使用
chcp 65001
)。 - 保存文件为 UTF-8(无 BOM)。
- 确保
- 实例变量未初始化:
- 原因:访问未定义的实例变量返回
nil
。 - 解决:
ruby def initialize(name) @name = name || "默认姓名" end
- 继承或模块错误:
- 原因:未正确调用
super
或模块未混入。 - 解决:
- 检查
super
参数是否匹配父类。 - 确保
include
模块名称正确。
- 检查
7. 最佳实践
- 编码统一:始终使用 UTF-8,避免 GBK 除非必要。
- 命名规范:类名使用驼峰式(
CamelCase
),方法名使用下划线(snake_case
)。 - 模块化:使用模块组织通用功能,提高代码复用性。
- 异常处理:
begin
File.read("不存在.txt", encoding: "UTF-8")
rescue Errno::ENOENT
puts "文件不存在!"
end
8. 进阶建议
- Rails 集成:
- 在 Rails 中,类常用于模型:
ruby class User < ApplicationRecord validates :name, presence: true end
- 使用
i18n
gem 处理中文:# config/locales/zh-CN.yml zh-CN: hello: "你好"
- 调试工具:
- 使用
pry
检查对象:gem install pry
require 'pry' student = Student.new("小明", 18, "A") binding.pry # 检查 student.instance_variables
- 测试框架:
- 使用 RSpec 测试类:
bash gem install rspec
ruby describe Student do it "returns correct introduction" do student = Student.new("小明", 18, "A") expect(student.introduce).to eq("学生姓名:小明,年龄:18岁,成绩:A") end end
9. 社区资源
- Ruby 官方文档:ruby-doc.org
- Ruby China:ruby-china.org
- 《Programming Ruby》(Pickaxe Book)
通过以上案例,你可以掌握 Ruby 类和对象的实际应用,并处理中文相关任务。如果需要更复杂的案例(如数据库操作、Rails 模型)或针对某个案例的深入讲解,请告诉我!