Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort_by date in Ruby (not Rails)?

Tags:

ruby

I know that Rails has sorting methods built into ActiveRecord, but I am just writing a plain-old ruby script and would love to sort the records from an array by date.

The date would be stored in one of the cells of the multi-dimensional array.

What's the best way for me to approach this, so I can get to the point where I just do sort_by_date and I indicate either ASC or DESC?

I don't have to use the method sort_by_date, but the idea is I would like to be able to easily call a method on the collection and get the results I want.

Thoughts?

like image 696
marcamillion Avatar asked May 25 '12 14:05

marcamillion


People also ask

How to sort data in Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.

How to sort the array in Ruby?

You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)


2 Answers

def sort_by_date(dates, direction="ASC")
  sorted = dates.sort
  sorted.reverse! if direction == "DESC"
  sorted
end
like image 195
fl00r Avatar answered Dec 22 '22 17:12

fl00r


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.

like image 41
DanS Avatar answered Dec 22 '22 18:12

DanS