How to sort_by date in Ruby (not Rails)?
def sort_by_date(dates, direction="ASC")
sorted = dates.sort
sorted.reverse! if direction == "DESC"
sorted
end
Something like this?
class Array
def sort_by_date(direction="ASC")
if direction == "ASC"
self.sort
elsif direction == "DESC"
self.sort {|a,b| b <=> a}
else
raise "Invalid direction. Specify either ASC or DESC."
end
end
end
A multi-dimensional array is just an array of arrays, so call this method on the 'dimension' you want to sort.
The way I am doing it right now it is:
@collection.sort! { |a,b| DateTime.parse(a['date']) <=> DateTime.parse(b['date']) }
And with the ! operator I am affecting the same variable (otherwise I will need another one to hold the modified variable). So far, it's working as a charm.