HeadFirst Ruby 第十章总结 Comparable & Enumerable

导言

这一章的标题是 Ready-Made Mixes, 也就是 Ruby 已经准备好的用于 Mix-in 的 Modules, 它们是: Comparable 和 Enumerable, Comparable 常用于比较数字, Enumerable 常用于 Collection 形式的数据.本章介绍了:

  1. 如何mix in Comparable 这个 Module
  2. 如何mix in Enumerable 这个 Module

如何使用 Comparable 这个 Module

定义:

Comparable 包含的 methods 有:

  • >
  • >=
  • <
  • <=
  • ==
  • between?

注意:在 Ruby 中,比较运算符的实质是数字类型数据对象(包含 Fixnum 和 Float 对象)的 method.
比如,4 > 3 的实质是 4调用了 .> (second_number ) 的方法,传入了 3 这个参数.

基础:定义 "<=>"这个 method

定义

<=> 名称叫做 "spaceship operator",它通过比较两边的值返回 -1, 0, 1 等值.

自我实现:

module Comparable
def <(other)
(self <=> other) == -1
end

def >(other)
(self <=> other) == 1
end

def ==(other)
(self <=> other) == 0
end

def <=(other)
comparison = (self <=> other)
comparison == -1 || comparison == 0
end

def >=(other)
comparison = (self <=> other)
comparison == 1 || comparison == 0
end

def between?(first, second)
(self <=> first) >= 0 && (self <=> second) <= 0
end
end

Comparable 包含的各种方法的基础是 "<=> 方法,它们是通过这个方法来进行运算并且给出判断值的.

如何使用 Enumerable 这个 method

定义

Enumerable 这个 module 包含的常见的 methods 有:

  • find_all
  • refuse
  • map

总共包含了 50 个方法.

基础: each 方法

Enumerable 的基础是 each 这个 method ,因此需要在使用的 object 中创建 each 这个方法.

自我实现:

以分隔单词为例:

def each
string.split(" ").each do |word|
yield word
end
end





posted @   FBshark  阅读(124)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示