Sorting (Reverse?)


#1

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:

fruits.sort!.reverse!

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


#2

Hey

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
books.sort!

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
end

puts books

#3

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

#5

Another alternative is to use the sort_by method :slight_smile:

Example:

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

Another example:

fruits.sort_by(&:length)

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