# 19/19 sort method logic question

#1

I can achieve the correct result with
fruits.sort! {|fruit1, fruit2| fruit2<=>fruit1 }

But I dont understand how sort() actually Sorts the array of fruits. I started with
fruits.sort.reverse!
but this was no good. Is that just for the purpose of the exercise?

What does sort() do with the block argument {|fruit1, fruit2| fruit2<=>fruit1 } on its five entries in order to sort it? Why is this preferable to just sort.reverse()?

#2

@joshgreaves332, In this case sorting the fruits put the in reverse alphabetical order. If you put :

fruits.sort! {|fruit1, fruit2| fruit1<=>fruit2 },

it would put them in alphabetical order. This is because you put fruit2 in front of fruit1.

The result is:
["pear", "orange", "grapes", "banana", "apple"]

#3

Yes I totally understand how to achieve that, thanks for your response.

My problem is understanding what exactly the sort() method does with that block argument to its five entries to achieve that result?

#4

Well think of it like this. Every fruit gets compared against every other fruit. So every single item on the array will be both fruit1, and fruit2 comparing against every other item in the array. The computer is just able to do this really fast so it's hard to comprehend.

fruit1: apple <=> fruit2: pear, orange, grapes, banana
fruit1: banana <=> fruit2: pear, orange, grapes, apple
etc.

And it does this comparison between each and every item allowing it to find it's position in the array. As it sorts the array it finds where each items it suppose to be and assigns it to that location because we used the ".sort!" method.

#5

Thankyou that is clear. It just seems over complex due to the fact sort() already contains the algorithm, so why can't we remain high level and just say "sort it please" instead of saying "sort it one at a time and use this comparative method on individual pairs"?

Am I being overly difficult, I have a habit...