From: Gavin Kistner Date: 2004-10-04T22:04:12+09:00 Subject: Re: How to sort a table in Ruby? On Oct 4, 2004, at 3:14 AM, Robert Klemme wrote: >> a.sort { |x,y| x[3] <=> y[3] } # sort on 4th element > That's even better: > a.sort_by {|row| row[3]} The reason that #sort_by is better than #sort is described in the documentation. In short (IIRC) it's because it caches the key values for each row (performing the block only once for each row) and uses those to sort, rather than invoking the block for every unique pair it has to compare. A downside, however, is the inability to specify something like a reverse sort. (Although for that case you can just reverse the array afterwards.) Actually, does anyone have a compelling example where #sort produce a result (which is reasonable) which #sort_by cannot? (By 'reasonable' I mean that something like a.sort{ |x,y| x[3] <=> y[7] } does something impossible for #sort_by, but probably would produce erratic results, given no way of knowing in which order the pairs come.)