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?
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With