Sorting (Reverse?)


I tried looking through but couldn't find an answer. Throughout this section, it talks about sorting in reverse and using the comparison method to sort it from end to beginning. Why is using:


not a viable option? Or is it and it's just reiterating the whole "Ruby has multiple ways of doing everything" concept?



Using fruits.sort!.reverse! is a perfectly viable option, and yes, I suppose part of the point is to show how multiple ways can be done for the same thing

However, another option that the combined comparison operator allows, is that you can now decide yourself how you want things to be sorted, based on how you need it

Taking the example variable below, I could sort a string array using normal sort, or for my own needs

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

#I can sort it alphabetically, which Ruby supports normally

puts books

#I can sort it by the length of each title, by comparing the .length method of each string
books.sort! do |first_book, second_book|
    first_book.length <=> second_book.length

puts books


You can try this simple way:

fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! do |firstfruit, secondfruit| firstfruit <=> secondfruit end
fruits.reverse! do |firstfruit, secondfruit| firstfruit <=> secondfruit end


Another alternative is to use the sort_by method :slight_smile:


fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort_by { |fruit| fruit.length }

Another example:


Don't let the &:length confuse you, it produces the same result. It's just a shortcut :slight_smile: