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

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

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

6条回答
  •  暖寄归人
    2020-11-22 15:18

    Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.

    For example, if I have an array of objects I can do things like this:

    # `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
    

    This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.

提交回复
热议问题