In the following, the results are the same:
[3, 5].sort{|a, b| b <=> a}
[5, 3].sort{|a, b| b <=> a}
I would like to know what happened internally and how it depends on input array.
In the following, the results are the same:
[3, 5].sort{|a, b| b <=> a}
[5, 3].sort{|a, b| b <=> a}
I would like to know what happened internally and how it depends on input array.
The first line:
[3, 5].sort { |a, b| b <=> a }
Invokes the block with a = 3
and b = 5
. It returns the result of 5 <=> 3
which is 1
. An integer greater than 0
tells sort
that a
follows b
. The result is therefore [5, 3]
.
The second line:
[5, 3].sort { |a, b| b <=> a }
Invokes the block with a = 5
and b = 3
. It returns the result of 3 <=> 5
which is -1
. An integer less than 0
tells sort
that b
follows a
. The result is therefore (again) [5, 3]
.
Because you are sorting an array, and changing the array's elements order does not change the sorting result.
This is the whole point of sorting after all - to get sorted result despite the initial arrays ordering.
To change the result, you will want to change the sorting rule, not the array.
The output is the same regardless of the input order because you sorting the array.
If you want to sort with the opposite order write
[3,5].sort{|a,b| a <=> b}