Comparable模块对象的排序。继承该模块的类必须定义<=>方法,用于比较该类和另一个对象,通过是小于,等于,还是小与,返回-1,0,或者+1。如果两外一个对象没有继承Comparable,则返回nil。Comparable使用<=>来继承传统的<, <=, ==, >=, 和 >比较操作符和方法between?

class SizeMatters
  include Comparable
  attr :str
  def <=>(anOther)
    str.size <=> anOther.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]

天赢金创
338 声望21 粉丝

天赢金创,天赢金创,天赢金创,天赢金创,天赢金创,天赢金创天赢金创,天赢金创


引用和评论

0 条评论