Ruby 中的 Comparable 模組


在 Ruby 中,可以用Comparable mixin對可以排序的類例項執行排序。類定義需要包含一個運算子,以將接收者相互比較。運算子將返回 -1、0 或 1。

  • 如果接收者小於另一個物件,則它將返回-1

  • 如果它大於另一個物件,則它將返回1

  • 如果接收者等於另一個物件,則它將返回0

在 Comparable 模組中,運算子<=>用於實現常規比較運算子(*、<=、==、>=>),有時也用作between?方法。

現在我們對 Ruby 中的 Comparable 模組有了一些瞭解,接下來讓我們探索一些相關的示例。

示例 1

考慮如下所示的程式碼

class TutorialsPoint

# comparable module
include Comparable
attr :key

   def <=>(other_key)
      key.length <=> other_key.key.length
   end

   def initialize(key)
      @key = key
   end
end

# creating objects
a1 = TutorialsPoint.new("T")
a2 = TutorialsPoint.new([3, 6])
a3 = TutorialsPoint.new("tuts")

# comparable operator
puts a1 < a2

# using between? method
puts a2.between?(a1, a3)
puts a3.between?(a1, a2)

輸出

true
true
false

在上面的示例中,我們只使用了一個運算子進行比較;還有 5 個這樣的運算子可用。

示例 2

考慮如下所示的程式碼,它描述了使用所有這些比較運算子的情況。

class TutorialsPoint

# comparable module
include Comparable
attr :key

   def <=>(other_key)
      key.length <=> other_key.key.length
   end

   def initialize(key)
      @key = key
   end
end

# creating objects
a1 = TutorialsPoint.new("T")
a2 = TutorialsPoint.new([3, 6])
a3 = TutorialsPoint.new("tuts")

# comparable operators
puts a1 < a2
puts a1 <= a2
puts a1 == a2
puts a1 >= a2
puts a1 > a2

輸出

true
true
false
false
false

更新日期:2022 年 1 月 25 日

365 次瀏覽

啟動你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.