Sort! internal working


#1

books.sort! { |firstBook, secondBook| puts firstBook <=> secondBook } how is the sorting happening internally.What will be the value of firstbook and secondbook the very first time and how does the sorting works internally.
Thank You for the help


#2

There should not be a puts in the block. only the sort directive.

array.sort!

is an in-place method that acts directly upon the array, without making a copy

array.sort! { | a, b | a <=> b }

When the combined comparision operator is used, it performs a swap if the order is not as specified by the order of the operands.

Given `| a, b |` in the block parameters
a <=> b will swap  a and b if a is greater, or comes after, b.
b <=> a will sway b and a if b is less than a

The first is an ascending order sort, the second a descending order sort. To study how this technique might be working in the background (internally) read up on merge sort.


#3

Thank You for your reply