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

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

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

6条回答
  •  悲哀的现实
    2020-11-22 15:38

    The spaceship method is useful when you define it in your own class and include the Comparable module. Your class then gets the >, < , >=, <=, ==, and between? methods for free.

    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.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 # [#, #, #]
    

提交回复
热议问题