15 - Sort in descending order


#1



So, below there's the code that makes the exercise work


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

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?


#2

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


#3

Yeah, I got this.
Just trying to understand why


#4

You're contradicting yourself.

"I understand. I don't understand"

Be specific.

You might go read wikipedia's article on comparison sorts


#5

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


#6

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.


#7

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


#8

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


#9

I don't get this exercise at all.

Why can't I just do:

books.sort.reverse!

and go on with my life?


#10

try books.sort!.reverse!


#11

Just change the order around:

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


#12

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, <=>.


#13

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.


#14

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