From: Florian Gross Date: 2004-10-05T02:54:53+09:00 Subject: Re: How to sort a table in Ruby? Gavin Kistner 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.) It is possible when you want to sort by something that can be expressed as a number: persons.sort_by { |person| -person.age } Regards, Florian Gross