From: John Joyce Date: 2007-10-18T01:21:37+09:00 Subject: Re: sort_by On Oct 17, 2007, at 10:55 AM, mortee wrote: > Paulo Carvalho wrote: >> Hello >> >> 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? > > what about > > @values_ordered = @values.sort_by { |e| -e.id_column } > > mortee > > Is it Rails? If so, ActiveRecord has a way to do this with a database table's values by using a hash option, order => DESC If you're using a database, you should consider ActiveRecord itself. There is also Ruby DBI, which allows pretty much plain SQL action. Either one will make life much easier working with a database. There is also OG (another ORM) The question I have is, Is your list of rows a multi-dimensional Array? If so, and I am assuming it is, you can use the Array indices like columns for sort_by Use irb (and ri to check some docs) to compare : Array.sort Array.sort { |a, b| block } sort can also take a block and might be what you want. a = [ "d", "a", "e", "c", "b" ] a.sort #=> ["a", "b", "c", "d", "e"] a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]