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
You’re currently reading “Enumerable#sort_by{rand}”, an entry on Brandt.Kurowski.net
- Published:
- January 4th, 2008 22:40
- Updated:
- January 5th, 2008 04:08
- Previous:
- Consolidating
- Next:
- Helvetica

0 comments
Jump to comment form | comments rss [?]