From: mortee Date: 2007-10-12T12:48:40+09:00 Subject: Re: sort double-dimensional array by column Mr_Tibs wrote: > Hi, > > I have a [m X n] double-dimensional array in Ruby and I'm trying to > sort the entries (rows) by the 6-th column, which is a DateTime > object. Things get a little bit complicated, since I might have a nil > value in that column. If that happens, then I want to sort by the 7-th > column. > This is what I have so far: > > cset_arr = cset_arr.sort do |x, y| > if x[5].nil? && y[5].nil? > x[6] <=> y[6] > elsif x[5].nil? && !y[5].nil? > y[5] # ??? > elsif !x[5].nil? && y[5].nil? > x[5] # ??? > elsif !x[5].nil? && !y[5].nil? > x[5] <=> y[5] > end > end What about this one? cset_arr.sort_by{|row| [ row[5] || DateTime.new, row[6] ] } Comparing two arrays returns the comparison of the first differing pair of respective elements. DateTime.new returns some value far in the past, I guess the lowest possible value. So if both dates are nil, then the first value in the sort key become the same (this default DateTime value), thus the 7th column gets compared. Otherwise nil gets replaced by a value which is most probably lower than any meaningful one. mortee