什么是Ruby <=>(太空船)运营商?

Jus*_*ier 250 ruby operators comparison-operators spaceship-operator

什么是Ruby <=>(宇宙飞船)运营商?运营商是否通过其他语言实施?

Ton*_*rra 336

Perl可能是第一种使用它的语言.Groovy是另一种支持它的语言.基本上,而不是返回1(true)或0(false取决于参数是否相等或不相等),飞船运算符将返回1,0或者?1取决于相对于右参数左边参数的值.

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
Run Code Online (Sandbox Code Playgroud)

它对排序数组很有用.

  • 究竟.我认为它是Java的Comparable的一个非常优雅的版本. (27认同)
  • c#中的模拟是IComparable.CompareTo (12认同)
  • 实际上我认为任何负值或正值都可以返回。0仍然意味着平等。 (2认同)
  • 请注意,如果比较的两个对象不具有可比性,则会得到一个零 (2认同)

ste*_*lag 67

当您在自己的类中定义并包含Comparable模块时,spaceship方法很有用.然后你的班级>, < , >=, <=, ==, and between?免费获得这些方法.

class Card
  include Comparable
  attr_reader :value

  def initialize(value)
    @value = value
  end

  def <=> (other) #1 if self>other; 0 if self==other; -1 if self<other
    self.value <=> other.value
  end

end

a = Card.new(7)
b = Card.new(10)
c = Card.new(8)

puts a > b # false
puts c.between?(a,b) # true

# Array#sort uses <=> :
p [a,b,c].sort # [#<Card:0x0000000242d298 @value=7>, #<Card:0x0000000242d248 @value=8>, #<Card:0x0000000242d270 @value=10>]
Run Code Online (Sandbox Code Playgroud)


gno*_*ice 19

这是一般的比较运算符.它返回-1,0或+1,具体取决于其接收器是否小于,等于或大于其参数.


Ani*_*rya 15

我将用简单的例子来解释

  1. [1,3,2] <=> [2,2,2]

    Ruby将从左侧开始比较两个数组的每个元素. 1对于左数组小于2右数组.因此左数组小于右数组.输出将是-1.

  2. [2,3,2] <=> [2,2,2]

    如上所述,它将首先比较第一个相等的元素,然后比较第二个元素,在这种情况下,左数组的第二个元素更大,因此输出为1.

  • @KickButtowski 它会继续比较其他元素,除非找到不相等的数字。 (2认同)

lil*_*ole 5

由于此运算符减少了与整数表达式的比较,因此它提供了基于多个列/属性对升序或降序进行排序的最通用方法。

例如,如果我有一个对象数组,我可以执行以下操作:

# `sort!` modifies array in place, avoids duplicating if it's large...

# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }

# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }

# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }

# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
      8 * (a.zip   <=> b.zip) +
     -4 * (a.age   <=> b.age) +
      2 * (a.last  <=> b.last) +
          (a.first <=> b.first)
end
Run Code Online (Sandbox Code Playgroud)

这个基本模式可以概括为按任意数量的列排序,在每个列上以任何升序/降序排列。

  • 好吧,也许我会详细说明一下:对于因子 (4,-3,2,1) 和宇宙飞船操作的结果 (1,1,-1,-1),加权和是 -2,但是它需要是积极的!否则,较大的拉链将位于较小的拉链之前。对于因子 (8,-4,2,1),这种情况不会发生。 (2认同)