19. Sorting | I don't understand .sort


#1

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]

# To sort our books in ascending order, in-place
books.sort! { |firstBook, secondBook| firstBook <=> secondBook }

# Sort your books in descending order, in-place below
books.sort! { |firstBook, secondBook| secondBook <=> firstBook }

["War and Peace", "Utopia", "Charlie and the Chocolate Factory", "A Wrinkle in Time", "A Brief History of Time"]

on Codecademy.

But, I don't understand what <=> has to do with .sort

https://www.codecademy.com/en/courses/ruby-beginner-en-ET4bU/4/4


#2

Please see http://stackoverflow.com/a/827656/2675672

It is related to .sort method because that method arranges two values in an array based on a positive, negative or 0 value. If a positive value is passed, the order of first and second value is reversed. The spaceship operator returns a positive negative or 0 value and thus helps in this sorting method.