'<==>'是什么意思?在鲁比?

发布于 2024-10-29 13:58:02 字数 870 浏览 5 评论 0 原文

'<==>'是什么意思在鲁比?

示例:该代码来自以下类,该类比较 xxx 格式的数字,

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

以下代码来自该类,该类对 xxx 等数字进行排序,

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

What is the meaning of '<==>' in Ruby?

Example: The code comes from the following class that compares numbers in the format x.x.x,

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

The following code comes from this class that orders numbers like 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

来世叙缘 2024-11-05 13:58:02

那是宇宙飞船操作员。然而,它实际上是 <=> (而不是 <==>)。

虽然这不是它的官方名称,但我确信它是该运营商最常用的名称。它是一个比较运算符,其中

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

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

That is the spaceship operator. However, it is actually <=> (not <==>).

Although that is not its official name, I'm sure, it's the most commonly used name for that operator. It is a comparison operator where

  • If other is less than self, return 1,
  • If other is equal to self, return 0
  • If other is greater than self, return -1

It is a powerful operator in that by just implementing this you can do sorting of your own type and participate in a lot of other niceties, like the Enumerable mixin.

栀梦 2024-11-05 13:58:02

你为什么不尝试一下呢?只需输入您发布的代码,您就可以很容易地发现它没有任何意义,因为 <==> 在 Ruby 中不是有效的方法名称。您发布的代码只会引发 SyntaxError

Why don't you just try it out? By just typing in the code you posted, it is trivial to see for yourself that it doesn't mean anything, since <==> is not a valid method name in Ruby. The code you posted will just raise a SyntaxError.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文