From: Stefan Rusterholz Date: 2009-01-24T19:16:29+09:00 Subject: Re: Sorting array with nils (RK) Sentinel wrote: > def sort categ, column, descending=false > d = get_records_for_category categ > d = d.sort { |y,x| > if descending > if x[column].nil? > true # <<<<------------- errors --- yes of course, <=> expectes -1,0,1, not true/false > elsif y[column].nil? > false # <<<<------------- errors too, for the same reason > else > x[column] <=> y[column] > end > else > if x[column].nil? > 1 # <<<-------------- gives errors --- no, should not > elsif y[column].nil? > -1 > else > y[column] <=> x[column] > end > end > } > return d > end A solution (untested): class Uncomparable def initialize(always_less=true) @compare = always_less ? -1 : 1 end def <=>(other) Uncomparable === other ? 0 : @compare end end ... d.sort_by { |row| row[column] || Uncomparable(!descending) } ... Depending on what end you want the nils, you have to change !descending to just descending. Regards Stefan -- Posted via http://www.ruby-forum.com/.