本文簡要介紹ruby語言中 Comparable模塊
的用法。
Comparable
mixin 由其對象可以排序的類使用。該類必須定義 <=>
運算符,它將接收者與另一個對象進行比較,返回小於 0 的值、返回 0 或返回大於 0 的值,具體取決於接收者是小於、等於還是大於比其他對象。如果另一個對象不可比較,則 <=>
運算符應返回 nil
。 Comparable
使用 <=>
來實現傳統的比較運算符(<
、<=
、==
、>=
和>
)和方法between?
。
class SizeMatters
include Comparable
attr :str
def <=>(other)
str.size <=> other.str.size
end
def initialize(str)
@str = str
end
def inspect
@str
end
end
s1 = SizeMatters.new("Z")
s2 = SizeMatters.new("YY")
s3 = SizeMatters.new("XXX")
s4 = SizeMatters.new("WWWW")
s5 = SizeMatters.new("VVVVV")
s1 < s2 #=> true
s4.between?(s1, s3) #=> false
s4.between?(s3, s5) #=> true
[ s3, s2, s5, s4, s1 ].sort #=> [Z, YY, XXX, WWWW, VVVVV]
相關用法
- Ruby Comparable.between?用法及代碼示例
- Ruby Comparable.clamp用法及代碼示例
- Ruby Complex.arg用法及代碼示例
- Ruby ComposedSet類用法及代碼示例
- Ruby Complex.abs2用法及代碼示例
- Ruby Complex.angle用法及代碼示例
- Ruby Complex.polar用法及代碼示例
- Ruby Complex.to_f用法及代碼示例
- Ruby Complex.cmp / numeric用法及代碼示例
- Ruby Complex.conj用法及代碼示例
- Ruby Complex類用法及代碼示例
- Ruby Complex.infinite?用法及代碼示例
- Ruby Complex.abs用法及代碼示例
- Ruby Complex conjugate()用法及代碼示例
- Ruby Complex.phase用法及代碼示例
- Ruby Complex.rationalize用法及代碼示例
- Ruby Complex.cmp ==用法及代碼示例
- Ruby Complex.imaginary用法及代碼示例
- Ruby Complex.cmp * numeric用法及代碼示例
- Ruby Complex.fdiv用法及代碼示例
- Ruby Complex.rect用法及代碼示例
- Ruby Complex.inspect用法及代碼示例
- Ruby Complex abs用法及代碼示例
- Ruby Complex.magnitude用法及代碼示例
- Ruby Complex.-cmp用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Comparable模塊。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。