Friday, November 05, 2010

Date sort in ruby from array can have date formats ,non date formats

Date sorting(ruby) from array is easy if array contain strings with proper date formats. Sometime invalid date formats raise argument error.

Sample i have used  for date column attribute as follows.
def sort_on_mature_date(listings)
    listings.sort do |x,y|
      x_matures_on = x.when_does_it_mature? #date type
      y_matures_on = y.when_does_it_mature? #date type
      begin  Date.parse(x_matures_on)   rescue  x_matures_on="1900-1-1" end    #string could be not a date like "now"
      begin Date.parse(y_matures_on) rescue y_matures_on="1900-1-1" end
      Date.parse(x_matures_on)<=>Date.parse(y_matures_on)
    end
  end