Enumerable#sort_by{rand}

I came across this Ruby code today in a colleague’s work:

collection.sort_by{rand}

and was about to report it as a bug, since I had always assumed that sort_by required the comparison to be consistent, i.e. a <=> b should be equal to -(a <=> b), just as Java’s Comparable.compareTo requires. Then I realized that sort_by must not be calling the block for every comparison—it must be calling it once for each member of the collection, then using the results to sort the collection. Kinda like our friend the Schwartzian transform from Perl. Neato.


About this entry