如何在 Ruby(不是 Rails)中按日期排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10756175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:09:12  来源:igfitidea点击:

How to sort_by date in Ruby (not Rails)?

ruby

提问by marcamillion

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.

我知道 Rails 在 ActiveRecord 中内置了排序方法,但我只是在编写一个普通的 ruby​​ 脚本,并且希望按日期对数组中的记录进行排序。

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_dateand I indicate either ASCor DESC?

什么是对我来说,这种接近最好的方式,这样我就可以得到的地步,我只是做sort_by_date我表示要么ASC还是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.

我不必使用该方法sort_by_date,但我的想法是我希望能够轻松调用集合上的方法并获得我想要的结果。

Thoughts?

想法?

回答by fl00r

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

回答by DanS

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.

多维数组只是数组的数组,因此在要排序的“维度”上调用此方法。

回答by facundofarias

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.

并与!运算符我影响同一个变量(否则我将需要另一个变量来保存修改后的变量)。到目前为止,它是一种魅力。

回答by Jon Abrams

The following might not work for Date object, but should work for DateTime objects. This is because DateTime objects can be converted into an integer.

以下内容可能不适用于 Date 对象,但应该适用于 DateTime 对象。这是因为 DateTime 对象可以转换为整数。

I recently had to do a descending sort for DateTime objects and this is what I came up with.

我最近不得不对 DateTime 对象进行降序排序,这就是我想出的。

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

回答by carlitos

I'm using an old version of Rails and rabland it's works for me

我使用的是旧版本的 Rails rabl,它对我有用

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