ruby's <=> operator and sort method

前端 未结 3 1898
萌比男神i
萌比男神i 2020-12-23 12:46
player1 = Player.new(\"moe\")
player2 = Player.new(\"larry\",60)
player3 = Player.new(\"curly\", 125)
@players = [player1, player2, player3]

Above,

3条回答
  •  爱一瞬间的悲伤
    2020-12-23 13:37

    sort is actually an Enumerable method which relies on the implementation of <=>. From Ruby doc itself:

    If Enumerable#max, #min, or #sort is used, the objects in the collection must also implement a meaningful <=> operator, as these methods rely on an ordering between members of the collection.

    Try it yourself:

    class Player
      attr_accessor :name, :score
    
      def initialize(name, score=0)
        @name = name
        @score = score  
      end
    
      def <=> other
        puts caller[0].inspect
        other.score <=> score
      end
    end
    
    player1 = Player.new("moe")
    player2 = Player.new("larry",60)
    player3 = Player.new("curly", 125)
    @players = [player1, player2, player3]
    puts @players.sort.inspect
    
    #=> "player.rb:19:in `sort'"
    #=> "player.rb:19:in `sort'"
    #=> [#, #, #]
    

    You see, when we use sort on @players array, the object of Player is called with <=>, if you do not implement it, then you'll probably get:

    player.rb:14:in sort': comparison of Player with Player failed (ArgumentError) from player.rb:14:in'

    Which makes sense, as object doesn't know how to deal with <=>.

提交回复
热议问题