From: Rick DeNatale Date: 2007-03-20T07:43:57+09:00 Subject: Re: Sorting Dates and Times in an array On 3/19/07, Phrogz wrote: > If you write: > my_array.sort{ |a,b| a.long_calc <=> b.long_calc } > then you might have to perform that complex calculation 1,000,000 > times to sort your array. Less than ideal. > > If instead you write: > my_array.sort{ |person| person.long_calc } > then Ruby will first loop through your items and run long_calc for > each one, saving the values. Exactly 1,000 calls to long_calc. THEN it > will use those values to sort your original array, able to quickly > compare the saved result for each. > > > That's the performance reason to use sort_by. I personally use it > because it's much less typing. :) And of course, as the documentation for sort_by points out, it's not always wise to use it for performance reasons. According to the doc a = (1..100000).map {rand(100000)} a.sort runs an order of magnitude faster than: a.sort_by {|a| a} It's also not in general easy to come up with a sort_by block which does the kind of multi-attribute sort with different sort orders for each attribute that the OP was looking for. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/