【问题标题】:What is the meaning of '<==>' in Ruby? [duplicate]Ruby中的'<==>'是什么意思? [复制]
【发布时间】:2011-07-27 03:30:14
【问题描述】:

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

【问题讨论】:

标签: ruby-on-rails ruby spaceship-operator


【解决方案1】:

那是spaceship operator。然而,它实际上是&lt;=&gt;(不是&lt;==&gt;)。

虽然这不是它的正式名称,但我敢肯定,它是该运算符最常用的名称。它是一个比较运算符,其中

  • 如果other小于self,返回1,
  • 如果other等于self,返回0
  • 如果 other 大于 self,则返回 -1

它是一个强大的运算符,只需实现它,您就可以对自己的类型进行排序并参与许多其他细节,例如 Enumerable mixin。

【讨论】:

    【解决方案2】:

    你为什么不试试呢?只需输入您发布的代码,您就可以轻松地看到它没有任何意义,因为 &lt;==&gt; 在 Ruby 中不是有效的方法名称。您发布的代码只会引发SyntaxError

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2014-04-09
      • 2011-04-17
      • 2014-12-06
      • 2012-04-13
      • 2011-05-09
      • 1970-01-01
      • 2014-11-07
      • 2011-07-10
      相关资源
      最近更新 更多