15 getting technical. Alternative way



I just wanted to share an alternative way for this exercise.

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

To reverse the result, we can simply use the opposite of the return of the comparison operator.

  • -1 becomes 1
  • 1 becomes -1
  • and 0 becomes … 0

What do you think?


That works because it uses negative indexes. Clever. However it is a tiny detail that could get lost in the shuffle, and just one more thing to go wrong. I’d favor switching the parameters around to change order.


It’s fine in and of itself, and you’ll find this kind of thing often enough in definitions of comparison operators themselves. But you’re always going to prefer:


Which takes 5-10 times less time to read and understand
It also skips having to pass in a block, so it’s likely faster (though unlikely to be significant)

Edit: actually, somewhat significant

require 'benchmark'

sort_me = (1...100_000).to_a.shuffle

Benchmark.bm(10) do |x|
  x.report('sort.reverse   ') { sort_me.sort.reverse }
  x.report('sort with block') { sort_me.sort { |a, b| -(a <=> b) } }
                 user     system      total        real
sort.reverse     0.030000   0.000000   0.030000 (  0.022546)
sort with block  0.160000   0.010000   0.170000 (  0.162738)


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