Getting technical - Combined comparison


#1


https://www.codecademy.com/en/courses/ruby-beginner-en-ET4bU/3/4?curriculum_id=5059f8619189a5000201fbcb

I'm not stuck here, but I don't fully understand the logic behind it. Can anyone help me? Why are we not simply adding .reverse and instead add the combined comparison operator? And how does it extend the firstBook + secondBook logic to all books? I mean, why don't we need to call all the books?

Thanks!


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


#2

@anniething I agree that the <=> operator along with sorting can definitely be confusing when you try to understand the logic of what's happening!

Why are we not simply adding .reverse and instead add the combined comparison operator?

Adding .reverse to the first result as you mentioned is a totally valid way to get the same the result. The only downside of that approach is that it will take longer for Ruby to perform. Ruby will first have to sort the array, and once it's finished with that, it will then have to do some more work to reverse the array. With the approach of just using the <=> operator to sort the books in descending order, Ruby can get the same result but quicker.

how does it extend the firstBook + secondBook logic to all books?

Ruby is actually applying the { |firstBook, secondBook| firstBook <=> secondBook } concept to every book in the array. The confusing part is that when we see firstBook, we think "this must mean the first book in the array". What Ruby is doing in reality is choosing two books in the array and comparing them to each other, then taking another two books in the array and comparing them to each other, etc. So, firstBook and secondBook, mean the first book and second book in the context of any two books in the array that we're currently comparing.

I created a small program to which prints out some information about what Ruby is doing when it's sorting things. Sharing the results I saw might help you...

If I want to sort the array [4, 2, 1, 7] in ascending order I would do:

numbers = [4, 2, 1, 7]

numbers.sort { |first_number, second_number| first_number <=> second_number }

This is the output I got when I ran my program:

Comparing 4 and 2...
4 should come after 2

Comparing 1 and 7...
1 should come before 7

Comparing 2 and 1...
2 should come after 1

Comparing 2 and 7...
2 should come before 7

Comparing 4 and 7...
4 should come before 7

=> [1, 2, 4, 7]

If you'd like to see the program in action, you can run it here

Hopefully this makes things at least a little more clear.


#3

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