You are correct in that if our intent is simply to sort integers or strings in ascending/descending order, then the built-in available sort
and reverse
methods are perfectly suitable for the task and we don’t need these blocks of code.
However, the intent behind the exercises seems to be to equip us to handle more complex situations. If the sorting criteria is more convoluted, then we will need to write our own custom blocks of code. By understanding the simple and straightforward ascending/descending order blocks, we can familiarize ourselves us with the basic structure of the blocks and then we can implement our own logic/conditions for more complex sorting.
The basic structure of the blocks is that the sort method is going to go through an array. It will compare two elements at a time. We can either use the <=>
operator or if-else conditions to handle different situations. Either of -1, 0 or 1 will be returned. If 1 is returned, then we will swap the two elements. If 0 or -1 is the returned, then we leave the elements in their current positions. The blocks in the exercise for ascending/descending sort familiarize us with this structure for the simple and straightforward situation. Once we understand the basic structure, we can write our own blocks with more complex conditions and rules.
For the simple sorting of strings, you are correct. array.sort!
and array.reverse!
without any blocks of code are suitable. For more about the sort method, here is a useful and detailed explanation by Tony DiNitto