2017-06-02 76 views
0

我想我的数据作为时间表排序:如何使用Ruby on Rails对哈希表进行排序?

[ 
    { 
    "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" 
     ] 
     }, 
     .. 
    } 
] 

这里读了一些答案上做之后,我这次来到迄今:

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 

但我没有成功至今。任何想法如何按日期排序这些数据?

回答

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

上面会产生Date实例出字符串的,存储在根据每个后续散列"date"键。

由于@yzalavin的意见正确指出的那样,你可能想要实例DateTime使分拣更好:

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

也许'DateTime'? – yzalavin

+1

@yzalavin的确,谢谢,我只是复制了OP中的内容。 – mudasobwa

+0

哇!谢谢你,先生! Ruby社区真的很棒!我是RoR的新手,希望尽快回复你的帮助,好的,先生! –