2011-03-31 127 views
-4

在Ruby中'< ==>'是什么意思?Ruby中'<==>'的含义是什么?

例:代码来自下面的类,在格式x.x.x比较数字,

def <==>(other) 
    # Some code here 
end 

以下代码来源于此类的订单号码,如x.x.x

class Version 

    attr_reader :fst, :snd, :trd 
    def initialize(version="") 
     v = version.split(".") 
     @fst = v[0].to_i 
     @snd = v[1].to_i 
     @trd = v[2].to_i 
    end 

    def <=>(other) 
     return @fst <=> other.fst if ((@fst <=> other.fst) != 0) 
     return @snd <=> other.snd if ((@snd <=> other.snd) != 0) 
     return @trd <=> other.trd if ((@trd <=> other.trd) != 0) 
    end 

    def self.sort 
     self.sort!{|a,b| a <=> b} 
    end 

    def to_s 
     @sorted = @fst.to_s + "." + @snd.to_s + "." + @trd.to_s 
     #Puts out "#{@sorted}". 
    end 
end 
+7

我不认为这是有效的代码... – 2011-03-31 18:29:27

+0

现在我想知道[为什么只有一个等号](http://stackoverflow.com/questions/5508338/why-does-the-spaceship-运营商具备的,只有一法等号功能于它)。 – 2011-04-01 01:39:25

回答

12

spaceship operator。但是,它实际上是<=>(而不是<==>)。

尽管这不是它的正式名称,但我确定它是该运算符最常用的名称。这是一个比较操作符,其中

  • 如果其他小于自,返回1,
  • 如果其他等于自,返回0
  • 如果其他比自更大,返回-1

它是一个功能强大的操作员,通过实施这个功能,您可以对自己的类型进行排序并参与很多其他细节,例如Enumerable mixin。

3

你为什么不试试呢?只需输入您发布的代码,自己发现它并不意味着什么,因为<==>在Ruby中不是有效的方法名称。您发布的代码只会提高SyntaxError