From: John Joyce Date: 2007-10-18T01:25:30+09:00 Subject: Re: sort_by On Oct 17, 2007, at 11:04 AM, Rob Biedenharn wrote: > On Oct 17, 2007, at 11:12 AM, Paulo Carvalho wrote: >> Farrel Lifson wrote: >>> On 17/10/2007, Paulo Carvalho wrote: >>>> I have a list of rows which I want to order by a column. >>>> I make it with >>>> @values_ordered = @values.sort_by(&:id_column) >>>> >>>> What if I want to inverse the order (like order by x desc in SQL) >>>> >>>> How could I do that using sort_by? is that possible? >>> >>> values_orderd = @values.sort_by{|value| -value.id_column} >> >> Hello >> >> Thanks for your quick answer. >> >> However i am having a problem. >> >> I used the syntax that you give to me like this : >> >> To order (ASC way): >> values_ordered = @demandes.sort_by{|value| value.eluxid} >> (This one works fine) >> >> To order (DESC way) >> values_ordered = @demandes.sort_by{|value| -value.eluxid} >> This one send to me a syntax error (I think he dont like the '-'): >> undefined method `-@' for ["3CC11A"]:Array >> >> (note: "3CC11A" is the column value of my first row) >> >> Any idea of where is the problem? >> >> Thanks again >> >> -- Posted via http://www.ruby-forum.com/. > > If you don't have a way of giving your sortable value an inverse, > you may have to use .sort_by{|v|v.eluxid}.reverse or just use .sort > {|a,b| b.eluxid <=> a.eluxid } (note the swapping of the left- and > right-hand sides). > > When @demandes.size is "small enough" it's not necessarily faster > to use sort_by than just sort (particularly if computing a DESC > version of the sort key is "expensive"). > > -Rob > > Rob Biedenharn http://agileconsultingllc.com > Rob@AgileConsultingLLC.com > > > > Good Point! For large tables, it will be faster to use the database's abilities, so if the data set is large and you want the speed, go for DBI or ActiveRecord or OG or something. Many databases have optimized abilities for this. DESC is one of those.