如何使用Ruby on Rails对哈希表进行排序?

时间:2017-06-02 10:31:43

标签: ruby-on-rails ruby

我正在尝试将数据排序为时间轴

[
  {
    "date": "1996-07-16T08:26:01 -02:00",
    "isPublished": false,
    "events": [
      {
        "title": "occaecat aliqua dolor sint",
        "text": "Laboris nisi dolor ipsum pariatur veniam esse.",
        "picture": "http://placehold.it/32x32",
        "isPublished": true,
        "tags": [
          "elit",
          "incididunt",
          "consectetur"
        ]
      },
      ...
  },
  {
    "date": "1989-09-27T01:46:10 -01:00",
    "isPublished": false,
    "events": [
      {
        "title": "reprehenderit excepteur id minim",
        "text": "Commodo id officia est irure proident duis. Occaecat",
        "picture": "http://placehold.it/32x32",
        "isPublished": false,
        "tags": [
          "ex",
          "occaecat",
          "commodo"
        ]
      },
      ..
  }
]

在SO上阅读了一些答案之后,到目前为止,我来到这里:

class PagesController < ApplicationController
  require 'httparty'
  def index
    response = HTTParty.get('https://raw.githubusercontent.com/valterhenrique/timeliner-sample/master/sample-data.json')
    @dates = JSON.parse(response.body)
    @sorted_dates = @dates.sort_by {|s| Date.strptime(s, '%Y-%m-%d')}
    puts @new_dates
  end
  ...
end

但到目前为止我没有成功。知道如何按日期对这些数据进行排序吗?

1 个答案:

答案 0 :(得分:2)

@dates.sort_by { |s| Date.parse(s["date"]) }

以上将在字符串中生成Date实例,该实例在每个后续哈希中存储在"date"键下。

正如@yzalavin在评论中正确指出的那样,您可能希望实例化DateTime以更好地进行排序:

@dates.sort_by { |s| DateTime.parse(s["date"]) }