15/19 Getting Technical. How does this solution work?


I solved the lesson just doing


but I saw that the solution was different.
Actual solution:
books.sort! { |firstBook, secondBook| secondBook <=> firstBook }

How does that solution work? I thought the the combined comparison operator (<=>) just returned -1, 0, or 1. So how does reversing the arguments reverse the list?

edit: I guess i’m not too sure how the combined comparison operator works because I’m not sure how it sorts normally, ascending. How does the return values (-1, 0, 1) sort out an array of multiple values?


If you switch places on the values compared, you’ll get the opposite result, and therefore opposite order


Knew that.
But my question was Why? and How does it work.


You’re giving the sorting method code which it can use to determine which of two values goes before the other, which it can use to determine sort order

If you’re looking for something other than that, you’ll really have to say what that something is rather than “how”

And you were asking for that.


By the way, sorting and then reversing can be significantly faster because it avoids the overhead of calling a block:

require 'benchmark'

numbers = 1_000_000.times.map { rand }

Benchmark.bm do |x|
    x.report('sort then reverse:') { numbers.sort.reverse }
    x.report('sort with block:  ') { numbers.sort { |a,b| b <=> a } }
       user     system      total        real
sort then reverse:  0.421377   0.006398   0.427775 (  0.430189)
sort with block:    1.537772   0.003398   1.541170 (  1.549380)

Whether that matters or not depends on the use-case…


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