Comparable
mixin是Ruby核心的一部分。 可供可比较的类使用。 它包括一堆用于对象比较的方法。
例如, Numeric
和String
类包含此mixin
irb> Numeric.ancestors
=> [数值,可比较,对象,内核,BasicObject]
irb> String.ancestors
=> [字符串,可比对象,对象,内核,BasicObject]
NB:请随意看一下这篇文章 如果您想了解有关Module#ancestors
方法的更多信息。
实现一个包含Comparable的类
假设我们要按个人资料的rank
属性进行比较
- 使用Ruby查找数组中出现次数最多的元素的两种方法。
- 使用R18n红宝石gem转换Ruby应用程序
- 为什么PEDAC像巧克力蛋糕
- 全局变量基础
- 项目1:还记得俄勒冈小径吗? 涉足Flatiron的CLI数据宝石项目
班级简介
包含可比
attr:等级
def初始化(等级)
@rank =等级
结束
def (其他配置文件)
等级 other_profile.rank
结束
结束
irb> profile21 = Profile.new(21)
=>#
irb> profile42 = Profile.new(42)
=>#
irb> profile84 = Profile.new(84)
=>#
irb> profile84> profile42
=>是的
irb> profile84 <profile42
=>错误
irb> profile84 == profile84
=>是的
irb> profile21 <= profile42
=>是的
irb> profile84> = profile42
=>是的
包含Comparable
mixin的类必须响应方法(也称为宇宙飞船运算符)。
Comparable
mixin中实现的所有方法( ==
, <=
, >=
, >
, <
等)都使用此方法。
由于rank
属性是Integer
(它是Numeric
类的直接子级),我们可以使用方法的
Numeric
实现来安全地比较每个排名。
可枚举
由于包含Comparable
mixin的类必须响应方法,因此可以调用
Enumerable#sort
方法对一系列profiles
进行排序。
实际上,默认情况下,将使用每个比较项的方法处理
sort
方法
irb>个人资料= []
=> []
irb> 10.downto(5){| n | 个人资料<< Profile.new(rand(1..n))}
=> 10
irb>个人资料
=> [
#<配置文件:0x00007fda9a079be0 @ rank = 8 >,
#<配置文件:0x00007fda9a079af0 @ rank = 6 >,
#<配置文件:0x00007fda9a079a00 @ rank = 3 >,
#<配置文件:0x00007fda9a079910 @ rank = 1 >,
#<配置文件:0x00007fda9a079820 @ rank = 2 >,
#<配置文件:0x00007fda9a079708 @ rank = 4 >
]
irb> profiles.sort
=> [
#<配置文件:0x00007fda9a079be0 @ rank = 1 >,
#<配置文件:0x00007fda9a079af0 @ rank = 2 >,
#<配置文件:0x00007fda9a079a00 @ rank = 3 >,
#<配置文件:0x00007fda9a079910 @ rank = 4 >,
#<配置文件:0x00007fda9a079820 @ rank = 6 >,
#<配置文件:0x00007fda9a079708 @ rank = 8 >
]
之间可比
我想向您介绍Comparable#between?
的Comparable#between?
方法。 此方法使您可以知道对象是否包含在范围内
irb> 12.between?(0,24)
=>是的
irb>'aaa'.weenween?('bbb','ccc')
=>错误
由于我们在Profile
类中包含了Comparable
mixin,因此我们可以使用between?
方法。 注意between?
比较是包容的
irb> profile21 = Profile.new(21)
=>#
irb> profile42 = Profile.new(42)
=>#
irb> profile84 = Profile.new(84)
=>#
irb> profile42.between?(profile21,profile84)
=>是的
irb> profile21.between?(profile21,profile84)
=>是的
irb> profile84.between?(profile21,profile84)
=>是的
瞧!
请让我注意attention
