0

I'm trying to sort my data as a timeline:

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

After reading some answers here on SO, I came with this so far:

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

But I had no success so far. Any idea of how to sort these data by date ?

1 Answer 1

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

The above will produce a Date instance out of the string, that is stored under "date" key in each subsequent hash.

As @yzalavin properly noted in comments, you might want to instantiate DateTime to make the sorting better:

@dates.sort_by { |s| DateTime.parse(s["date"]) }
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe DateTime?
@yzalavin indeed, thanks, I just copied what was in the OP.
WOW! Thank you sir! The Ruby community is really amazing! I'm new to RoR, and hope to repay your help soon, good sir!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.