15 - Sort in descending order


<Below this line, add a link to the EXACT exercise that you are stuck at.>
So, below there’s the code that makes the exercise work


books.sort! { |first, second| second <=> first }

<do not remove the three backticks above>

I can't understand how. In another post somebody else writes that the result of the comparison is sorted in descending order when the operands are not in the same order as the block parameters.
Pretty straightforward, I get this. But... WHY?
It isn't explained anywhere in the exercise instructions, so I assume I missed something and I should have known this before.
Can anybody explain?

If you switch places the result will be the opposite and they’ll be placed in opposite order

If you say 5 is greater than 10, then 5 gets placed after 10

Yeah, I got this.
Just trying to understand why

You’re contradicting yourself.

“I understand. I don’t understand”

Be specific.

You might go read wikipedia’s article on comparison sorts

I mean that I understand that switching the operands gives this result.
I don’t understand why that happens/how it works

You would ask me which of 10 and 5 is greater.

If I tell you 5 is greater, then you would place the 10 first.

If I tell you 10 is greater, then you would place the 5 first.

Without asking me at all, you would be unable to sort them. Based on which reply I give, you’ll sort them differently.

Right, but form what I’ve understood of the comparison operation, it will always tell me (correctly), that 10 is greater than 5.
But switching the operands makes it magically change the sorting order.
Why the switching makes the order to change, that’s what I can’t grasp

You’re comparing the left side to the right side
If it’s the <=> operator that you’re (not) asking about, then look up what it does

I don’t get this exercise at all.

Why can’t I just do:


and go on with my life?

try books.sort!.reverse!

Just change the order around:

books.sort! { |firstBook, secondBook| secondBook <=> firstBook }

So the first thing I tried was { |secondBook, firstBook| secondBook <=> firstBook } and it came out ascending.

The “how” is |a, b| b <=> a, or that the first part, | |, is the reverse of the second, <=>.

I have to say, this lesson does not cover the “why?” of the challenge. I made a simple guess to switch the secondBook and firstBook for the <=> part and got it right on the first try. But I don’t understand why or how that is right.

Tell me where I am going wrong:

If I am comparing 5 to 10, it is going to tell me that 5 is less than 10, so I will put 5 in front of 10.

But if I compare 10 to 5 it is going to tell me that 10 is greater than 5 and will put it behind 5, still making it ascending and not descending order.


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