How .sort actually does sorting?


Methods, Blocks, & Sorting 5/19

Hey guys,

I'm having a hard time understanding how this code works. Although I can pass the exercise, I want to know what is actually happening before I move forward.

From my understanding:

fruits.sort! simply sorts the elements in the array in ascending order. We can modify the way it works by doing things like:

fruits.sort! do |firstfruit, secondfruit|
followed by code to compare the two fruits.

I was really curious about how it grabbed "firstFruit" and "secondFruit" out of the array so I made the code shown below.

I was expecting firstFruit to be "Orange" while the secondFruit to be "apple", but instead secondFruit was "Banana". Why is that? I thought it would grab "apple" since it's the 2nd element in the array.


fruits = ["orange", "apple", "banana", "pear", "grapes"]

fruits.sort! do |firstFruit, secondFruit|
    puts firstFruit
    puts secondFruit




That is printing, not comparing.

firstFruit <=> secondFruit

will sort in ascending order. Flip it around for descending order.

What is not readily evident is that internally, Ruby is comparing two items from the list at a time. If the higher value appears first, the two items are swapped. This continues until no more swaps can be made.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.