2017-06-02 7 views
0

私はタイムラインとしての私のデータをソートしようとしている:SOにここにいくつかの答えを読んだ後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

WOW!ありがとうございます! Rubyコミュニティは本当に素晴らしいです!私はRoRには新しく、すぐにあなたの助けを返すことを願っています。 –

関連する問題