What is the Ruby <=> (spaceship) operator?

后端 未结 6 1856
夕颜
夕颜 2020-11-22 14:42

What is the Ruby <=> (spaceship) operator? Is the operator implemented by any other languages?

6条回答
  •  爱一瞬间的悲伤
    2020-11-22 15:30

    Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1 (true) or 0 (false) depending on whether the arguments are equal or unequal, the spaceship operator will return 1, 0, or −1 depending on the value of the left argument relative to the right argument.

    a <=> b :=
      if a < b then return -1
      if a = b then return  0
      if a > b then return  1
      if a and b are not comparable then return nil
    

    It's useful for sorting an array.

提交回复
热议问题