【问题标题】:Is there any use of ruby combined comparison operator/spaceship operator other than in sorting?除了排序之外,还有没有使用 ruby​​ 组合比较运算符/宇宙飞船运算符?
【发布时间】:2016-06-10 02:30:25
【问题描述】:

Ruby 的组合比较运算符或宇宙飞船运算符用于排序。我用这个算子和sort函数一起使用,无法理解这个算子的机制。这个运算符还有其他用途吗?

【问题讨论】:

  • 从技术上讲,它不是运算符,而是您定义的方法。这意味着“任何其他用途”取决于您的想象和设计。所以你的问题的答案是“是”。

标签: ruby sorting spaceship-operator


【解决方案1】:

您基本上是在一个运算符中询问两个值是否大于、小于或等于。您可以使用它返回一个值来告诉方法递增、递减或什么都不做。

1 <=> 3 returns -1
3 <=> 1 returns 1
3 <=> 3 returns 0

例如,如果您有一种记分方法,您赢了一场比赛就得一分,输一场比赛就减一分,或者平局没有变化……

def score(player_1, player_2, current_score)
  current_score + player_1 <=> player_2
end

所以...

score(1,2,0)
#=> -1
score(1,3,-1)
#=> -2
score(3,2,-2)
#=> -1
score(3,0,-1)
#=> 0
score(4,0,0)
#=> 1
score(3,0,1)
#=> 2
score(3,3,2)
#=> 2

【讨论】:

  • 另一个常见的用法是在case 语句中。例如,case a&lt;=&gt;b; when -1 then ...; when 0 then ...; when 1 then ... ;.end
  • current_score 是一个局部变量。使用+= 分配给它没有意义。你应该只有+
【解决方案2】:

Comparable module 需要宇宙飞船运算符。基本上:include Comparable在你的班级中,在这个班级和 >、=、== 和之间定义一个 &lt;=&gt;method?为该类自动定义方法。

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 2010-11-25
    • 2011-03-04
    • 2010-10-24
    • 1970-01-01
    • 2015-06-10
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多