How to sort date in Ruby (not Rails)?

I know that Rails has sorting methods built into ActiveRecord, but I'm just writing a simple ruby โ€‹โ€‹script and would like to sort the entries from the array by date.

The date will be stored in one of the cells of the multidimensional array.

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

I do not need to use the sort_by_date method, but the idea is that I would like to easily call the method in the collection and get the results that I want.

Thoughts?

+7
source share
5 answers

Something like that?

  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 multidimensional array is just an array of arrays, so call this method on the โ€œdimensionโ€ that you want to sort.

+10
source
 def sort_by_date(dates, direction="ASC") sorted = dates.sort sorted.reverse! if direction == "DESC" sorted end 
+12
source

The way I'm doing it right now is:

 @collection.sort! { |a,b| DateTime.parse(a['date']) <=> DateTime.parse(b['date']) } 

And with! operator I touch the same variable (otherwise I will need another one to save the changed variable). While it works like a charm.

+4
source

The following steps may not work for a Date object, but should work for DateTime objects. This is because DateTime objects can be converted to an integer.

I recently had to do top-down sorting for DateTime objects, and this is what I came up with.

 def sort_by_datetime(dates, direction="ASC") dates.sort_by { |date| direction == "DESC" ? -date.to_i : date } end 
+3
source

I am using an old version of Rails and rabl and it works for me

 collection @name_of_your_collection.sort! { |a,b| DateTime.parse(a['start_at']) <=> DateTime.parse(b['start_at']) } node do |s| # lots of attributes s end 
0
source

Source: https://habr.com/ru/post/916677/


All Articles