player1 = Player.new(\"moe\")
player2 = Player.new(\"larry\",60)
player3 = Player.new(\"curly\", 125)
@players = [player1, player2, player3]
Above,
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 <=>.